Class JTextArea
JTextArea это многострочный область , которая отображает обычный текст. Он задуман как облегченный компонент, обеспечивающий совместимость исходного кода с классом java.awt.TextArea , где это возможно. Вы можете найти информацию и примеры использования всех текстовых компонентов в разделе Использование текстовых компонентов в Руководстве по Java.
Этот компонент имеет возможности, отсутствующие в классе java.awt.TextArea . Для получения дополнительных возможностей следует проконсультироваться с суперклассом. Альтернативными классами многострочного текста с расширенными возможностями являются JTextPane и JEditorPane .
java.awt.TextArea внутри ручки прокрутки. JTextArea отличается тем, что не управляет прокруткой, но реализует интерфейс Swing Scrollable . Это позволяет разместить его внутри JScrollPane , если требуется поведение прокрутки, и использовать напрямую, если прокрутка нежелательна.
java.awt.TextArea имеет возможность делать переносы строк. Это контролировалось политикой горизонтальной прокрутки. Поскольку JTextArea не выполняет прокрутку напрямую, обратная совместимость должна быть обеспечена другим способом. JTextArea имеет свойство bound для переноса строк, которое контролирует, будет ли он переносить строки. По умолчанию для свойства переноса строки установлено значение false (без переноса).
java.awt.TextArea имеет две rows свойств и columns , которые используются для определения предпочтительного размера. JTextArea использует эти свойства, чтобы указать предпочтительный размер области просмотра при размещении внутри JScrollPane , чтобы соответствовать функциональности, предоставляемой java.awt.TextArea . JTextArea имеет предпочтительный размер, необходимый для отображения всего текста, чтобы он правильно функционировал внутри JScrollPane . Если значение для rows или columns равно нулю, предпочтительный размер по этой оси используется для предпочтительного размера области просмотра по той же оси.
В java.awt.TextArea можно отслеживать изменения, добавляя TextListener для TextEvent s. В JTextComponent основе JTextComponent изменения транслируются из модели через DocumentEvent в DocumentListeners . DocumentEvent дает расположение изменения и вид изменения при желании. Фрагмент кода может выглядеть примерно так:
DocumentListener myListener = ??; JTextArea myArea = ??; myArea.getDocument().addDocumentListener(myListener);
Предупреждение: Swing не является потокобезопасным. Для получения дополнительной информации см . Политику потоковой передачи Swing .
Предупреждение: Сериализованные объекты этого класса не будут совместимы с будущими выпусками Swing. Текущая поддержка сериализации подходит для краткосрочного хранения или RMI между приложениями, использующими одну и ту же версию Swing. Начиная с версии 1.4, в пакет java.beans добавлена поддержка долгосрочного хранения всех компонентов JavaBeans . См. XMLEncoder .
Перенос строки в JTextArea
Как перенести строку не используя «\n», чтобы не было лишнего символа в строке? Или прям жестко разграничить Columns и Rows, чтобы переносило текст на новую строку насильно. А то колонки и строки указаны, а поле все равно растягивается, плюс обратиться к нужному элементу мешает «\n» если разграничивать им.
Добавлено через 27 секунд
Ну принудительно, мне кажется, подойдет лучше в данном контексте
Добавлено через 8 минут
Все, понял.
textArea.setPreferredSize(new Dimension(WIDTH, HEIGHT)); textArea.setLineWrap(true);
JPanel panel_south=new JPanel(); JTextArea textArea=new JTextArea(); Где ошибка?
JPanel panel_south=new JPanel(); JTextArea textArea=new JTextArea(); Label label=new JLabel(‘.
Перенос строки в Memo1 при достижении определённой длины строки
Здравствуйте. помогите. забуксовал. как правильно перенести строку в Memo1 при достижении.
При выводе строки на экран появляется не нужный перенос строки
Дорогие знатоки, проблема следующая: при выводе строки на экран появляется символ переноса строки.
Автоматический перенос на 2 строки вниз в конце каждой строки документа
Доброго времени суток. Работаю с архивом фотографий, есть вакуумная директория с N-ым кол-вом.
How to Use Text Areas
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.
Many of the Tutorial’s examples use uneditable text areas to display program output. Here is a picture of an example called TextDemo that enables you to type text using a text field (at the top) and then appends the typed text to a text area (underneath).
Click the Launch button to run TextDemo using Java™ Web Start (download JDK 7 or later). Alternatively, to compile and run the example yourself, consult the example index.
You can find the entire code for this program in TextDemo.java . 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.
Without the creation of the scroll pane, the text area would not automatically scroll. The JScrollPane constructor shown in the preceding snippet sets up the text area for viewing in a scroll pane, and specifies that the scroll pane’s scroll bars should be visible when needed. See How to Use Scroll Panes if you want further information.
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.
The following code adds text to the text area. Note that the text system uses the ‘\n’ character internally to represent newlines; for details, see the API documentation for DefaultEditorKit .
private final static String newline = "\n"; . textArea.append(text + newline);
Unless the user has moved the caret (insertion point) by clicking or dragging in the text area, the text area automatically scrolls so that the appended text is visible. You can force the text area to scroll to the bottom by moving the caret to the end of the text area after the call to append :
textArea.setCaretPosition(textArea.getDocument().getLength());
Customizing Text Areas
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.
The following code taken from TextSamplerDemo.java demonstrates initializing an editable text area. The text area uses the specified italic font, and wraps lines between words.
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);
By default, a text area does not wrap lines that are too long for the display area. Instead, it uses one line for all the text between newline characters and if the text area is within a scroll pane allows itself to be scrolled horizontally. This example turns line wrapping on with a call to the setLineWrap method and then calls the setWrapStyleWord method to indicate that the text area should wrap lines at word boundaries rather than at character boundaries.
To provide scrolling capability, the example puts the text area in a scroll pane.
JScrollPane areaScrollPane = new JScrollPane(textArea); areaScrollPane.setVerticalScrollBarPolicy( JScrollPane.VERTICAL_SCROLLBAR_ALWAYS); areaScrollPane.setPreferredSize(new Dimension(250, 250));
You might have noticed that the JTextArea constructor used in this example does not specify the number of rows or columns. Instead, the code limits the size of the text area by setting the scroll pane’s preferred size.
Another Example: TextAreaDemo
The TextAreaDemo example introduces an editable text area with a special feature a word completion function. As the user types in words, the program suggests hints to complete the word whenever the program’s vocabulary contains a word that starts with what has been typed. Here is a picture of the TextAreaDemo application.
Click the Launch button to run TextAreaDemo using Java™ Web Start (download JDK 7 or later). Alternatively, to compile and run the example yourself, consult the example index.
You can find the entire code for this program in TextAreaDemo.java .
This example provides a scrolling capacity for the text area with the default scroll bar policy. By default, the vertical scroll bar only appears when the display area is entirely filled with text and there is no room to append new words. You can provide a scroll pane of this type with the following code:
textArea.setWrapStyleWord(true); jScrollPane1 = new JScrollPane(textArea);
As mentioned above, the text area is editable. You can play with the text area by typing and pasting text, or by deleting some parts of text or the entire content. Also try using standard key bindings for editing text within the text area.
Now explore how the word completion function is implemented. Type in a word like «Swing» or «special». As soon as you have typed «sw» the program shows a possible completion «ing» highlighted in light-blue. Press Enter to accept the completion or continue typing.
The following code adds a document listener to the text area’s document:
textArea.getDocument().addDocumentListener(this);
When you started typing a word, the insertUpdate method checks whether the program’s vocabulary contains the typed prefix. Once a completion for the prefix is found, a call to the invokeLater method submits a task for changing the document later. It is important to remember that you cannot modify the document from within the document event notification, otherwise you will get an exception. Examine the following code below.
String prefix = content.substring(w + 1).toLowerCase(); int n = Collections.binarySearch(words, prefix); if (n < 0 && -n > 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; > >
The Text Area API
The following tables list the commonly used JTextArea constructors and methods. Other methods you are likely to call are defined in JTextComponent , and listed in The Text Component API.
You might also invoke methods on a text area that it inherits from its other ancestors, such as setPreferredSize , setForeground , setBackground , setFont , and so on. See The JComponent Class for tables of commonly used inherited methods.
The API for using text areas includes the following categories:
Examples That Use Text Areas
This table lists examples that use text areas and points to where those examples are described.
Example | Where Described | Notes |
---|---|---|
TextDemo | This section | An application that appends user-entered text to a text area. |
TextAreaDemo | This section | An application that has a text area with a word completion function. |
TextSamplerDemo | Using Text Components | Uses one of each Swing text components. |
HtmlDemo | How to Use HTML in Swing Components | A text area that enables the user to type HTML code to be displayed in a label. |
BasicDnD | Introduction to DnD | Demonstrates built-in drag-and-drop functionality of several Swing components, including text areas. |
FocusConceptsDemo | How to Use the Focus Subsystem | Demonstrates how focus works using a few components that include a text area. |