JAVA学习:文本框的设计与实现

本文介绍了JAVA中用于显示多行文本的JTextArea组件,对比了它与textField、editor pane、text pane及label的区别。JTextArea可通过设定行数和列数调整大小,通常默认可编辑,但可通过setEditable(false)设置为只读。此外,还讨论了如何设置字体、颜色、自动换行和缩进,以及启用拖放功能。文章提供了API的分类,包括内容设置、外观调整和功能实现。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

在JAVA的官方Tutorials中有这么一段话:

The JTextArea class provides a component that displays multiple lines of text and optionally allows the user to edit the text. If you need to obtain only one line of input from the user, you should use a text field. If you want the text area to display its text using multiple fonts or other styles, you should use an editor pane or text pane. If the displayed text has a limited length and is never edited by the user, use a label.

通过这段话,我们可知:对于要大段显示文字的应用场景,需要使用JTextArea,如果仅仅是为了获取一行文字,那么应给使用text field。如果想要实现多种字体和其他样式,那么就要使用editor pane 或者text pane。如果我们要显示的文字较短并且从来不用编辑,那么就直接用label就好了。

那么对于我的需求,我不需要花哨的样式,那么我仅仅使用JTextArea就好了。对于JTextArea的初始化,解释如下:

The following code creates and initializes the text area:

textArea = new JTextArea(5, 20);
JScrollPane scrollPane = new JScrollPane(textArea); 
textArea.setEditable(false);
The two arguments to the  JTextArea  constructor are hints as to the number of rows and columns, respectively, that the text area should display. The scroll pane that contains the text area pays attention to these hints when determining how big the scroll pane should be.

从官方解释我们可以看出,通过定义显示文字的行数和列数是可以定义这个text area 的大小的。而包在外边的scrollPane是为了保证滚动显示的。

Text areas are editable by default. The code setEditable(false) makes the text area uneditable. It is still selectable and the user can copy data from it, but the user cannot change the text area's contents directly.

其中默认的textarea是可以编辑的,就是说是可以改变其中的内容的。但是我们是可以通过setEditable(false)来将其设置为不可编辑,但是在这种状态下是可以将其选中并使用快捷键将其内容复制到剪切板的。

textArea.setCaretPosition(textArea.getDocument().getLength());//移动光标到文章的结尾
You can customize text areas in several ways. For example, although a given text area can display text in only one font and color, you can set which font and color it uses. This customization option can be performed on any component. You can also determine how the text area wraps lines and the number of characters per tab. Finally, you can use the methods that the  JTextArea  class inherits from the  JTextComponent  class to set properties such as the caret, support for dragging, or color selection.

虽然text area仅仅支持一种字体和颜色,但是我们可以定义它的字体和颜色,并且我们可以定义是否自动换行和缩进的所占的字符数。当然,我们可以使用JTextArea继承JTextComponent类的一些方法去设置一些属性,比如光标,是否支持拖放和颜色的选择。其中拖放很有意思。textArea.setDragEnabled(true); 大家可以试一试。

JTextArea textArea = new JTextArea(
    "This is an editable JTextArea. " +
    "A text area is a \"plain\" text component, " +
    "which means that although it can display text " +
    "in any font, all of the text is in the same font."
);
textArea.setFont(new Font("Serif", Font.ITALIC, 16));
textArea.setLineWrap(true);//自动换行
textArea.setWrapStyleWord(true);//使用空格来换行,如果放不下一个文字了
而且text area还支持单词的自动补充,就像其他编程IDE中函数的自动补全一样。

具体实现:

textArea.getDocument().addDocumentListener(this);// adds a document listener to the text area's document:
其中words = new ArrayList<String>(5);

String prefix = content.substring(w + 1).toLowerCase();
int n = Collections.binarySearch(words, prefix);
if (n < 0 && -n <= words.size()) {
    String match = words.get(-n - 1);
    if (match.startsWith(prefix)) {
        // A completion is found
        String completion = match.substring(pos - w);
        // We cannot modify Document from within notification,
        // so we submit a task that does the change later
        SwingUtilities.invokeLater(
            new CompletionTask(completion, pos + 1));
    }
} else {
    // Nothing found
    mode = Mode.INSERT;
}

The code shown in bold illustrates how the selection is created. The caret is first set to the end of the complete word, then moved back to a position after the last character typed. The moveCaretPosition method not only moves the caret to a new position but also selects the text between the two positions. The completion task is implemented with the following code:

  private class CompletionTask implements Runnable {
        String completion;
        int position;
        
        CompletionTask(String completion, int position) {
            this.completion = completion;
            this.position = position;
        }
        
        public void run() {
            textArea.insert(completion, position);
            textArea.setCaretPosition(position + completion.length());
            textArea.moveCaretPosition(position);
            mode = Mode.COMPLETION;
        }
    }
其中,是使用ENTER来完成自动补全的。

<span style="white-space:pre">		</span>InputMap im = textArea.getInputMap();
		ActionMap am = textArea.getActionMap();
		im.put(KeyStroke.getKeyStroke("ENTER"), COMMIT_ACTION);
		am.put(COMMIT_ACTION, new CommitAction());

The Text API:

The API for using text areas includes the following categories:

Setting or Obtaining contents
Method or ConstructorPurpose
JTextArea()
JTextArea(String)
JTextArea(String, int, int)
JTextArea(int, int)
Creates a text area. When present, the String argument contains the initial text. The int arguments specify the desired width in columns and height in rows, respectively.
void setText(String)
String getText()
(defined inJTextComponent)
Sets or obtains the text displayed by the text area.

Fine tuning the Text area's appearance
MethodPurpose
void setEditable(boolean)
boolean isEditable()
(defined inJTextComponent)
Sets or indicates whether the user can edit the text in the text area.
void setColumns(int);
int getColumns()
Sets or obtains the number of columns displayed by the text area. This is really just a hint for computing the area's preferred width.
void setRows(int);
int getRows()
Sets or obtains the number of rows displayed by the text area. This is a hint for computing the area's preferred height.
int setTabSize(int)Sets the number of characters a tab is equivalent to.
int setLineWrap(boolean)Sets whether lines are wrapped if they are too long to fit within the allocated width. By default this property is false and lines are not wrapped.
int setWrapStyleWord(boolean)Sets whether lines can be wrapped at white space (word boundaries) or at any character. By default this property is false, and lines can be wrapped (if line wrapping is turned on) at any character.

Implementing the Text area's functionality
MethodPurpose
void selectAll()
(defined in JTextComponent)
Selects all characters in the text area.
void append(String)Adds the specified text to the end of the text area.
void insert(String, int)Inserts the specified text at the specified position.
void replaceRange(String, int, int)Replaces the text between the indicated positions with the specified string.
int getLineCount()
int getLineOfOffset(int)
int getLineStartOffset(int)
int getLineEndOffset(int)
Utilities for finding a line number or the position of the beginning or end of the specified line.

本人总结:对于文本框的编程可以参考JAVA提供的例子进行,比较好理解。


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值