How to Stop Reading Text in Java When It Gets to the End

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 but one line of input from the user, y'all should use a text field. If y'all want the text expanse to brandish its text using multiple fonts or other styles, you lot should utilize an editor pane or text pane. If the displayed text has a limited length and is never edited by the user, apply a label.

Many of the Tutorial's examples utilize uneditable text areas to display program output. Hither is a picture of an instance called TextDemo that enables yous to type text using a text field (at the tiptop) and and then appends the typed text to a text expanse (underneath).

A snapshot of TextDemo

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.

Launches the TextDemo application

You tin can notice the entire code for this program in TextDemo.java. The following code creates and initializes the text expanse:

textArea = new JTextArea(five, 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 curlicue pane that contains the text area pays attention to these hints when determining how big the roll pane should be.

Without the creation of the scroll pane, the text area would not automatically curl. 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 roll bars should exist visible when needed. See How to Employ Curl Panes if yous want further data.

Text areas are editable by default. The code setEditable(false) makes the text area uneditable. Information technology is nonetheless selectable and the user tin re-create data from it, but the user cannot modify the text expanse'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 = "\northward"; ... textArea.append(text + newline);          

Unless the user has moved the caret (insertion point) by clicking or dragging in the text area, the text expanse automatically scrolls so that the appended text is visible. You can forcefulness 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

Yous can customize text areas in several ways. For example, although a given text expanse can display text in only one font and color, you can set which font and color information technology uses. This customization option can exist 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 prepare backdrop such as the caret, support for dragging, or color selection.

The following code taken from TextSamplerDemo.coffee demonstrates initializing an editable text area. The text surface area uses the specified italic font, and wraps lines between words.

JTextArea textArea = new JTextArea(     "This is an editable JTextArea. " +     "A text surface area is a \"plain\" text component, " +     "which ways that although it can display text " +     "in any font, all of the text is in the aforementioned font." ); textArea.setFont(new Font("Serif", Font.ITALIC, sixteen)); textArea.setLineWrap(truthful); textArea.setWrapStyleWord(true);          

Past default, a text expanse does not wrap lines that are also 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 phone call to the setLineWrap method 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 surface area in a gyre pane.

JScrollPane areaScrollPane = new JScrollPane(textArea); areaScrollPane.setVerticalScrollBarPolicy(                 JScrollPane.VERTICAL_SCROLLBAR_ALWAYS); areaScrollPane.setPreferredSize(new Dimension(250, 250));          

Yous 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 past setting the scroll pane's preferred size.

Another Example: TextAreaDemo

The TextAreaDemo instance introduces an editable text surface area with a special feature — a word completion function. Every bit the user types in words, the plan suggests hints to complete the word whenever the program'south vocabulary contains a word that starts with what has been typed. Here is a picture of the TextAreaDemo application.

A snapshot of TextAreaDemo

Click the Launch button to run TextAreaDemo using Java™ Web Start (download JDK 7 or afterward). Alternatively, to compile and run the example yourself, consult the example index.

Launches the TextAreaDemo Application

You can detect the entire code for this program in TextAreaDemo.java.

This case provides a scrolling capacity for the text area with the default roll bar policy. By default, the vertical curl bar only appears when the brandish area is entirely filled with text and there is no room to append new words. Y'all tin can provide a scroll pane of this type with the following code:

            textArea.setWrapStyleWord(truthful);   jScrollPane1 = new JScrollPane(textArea);          

As mentioned above, the text expanse is editable. Yous tin can play with the text area by typing and pasting text, or by deleting some parts of text or the unabridged content. Also attempt using standard key bindings for editing text within the text expanse.

Now explore how the give-and-take completion part is implemented. Type in a word similar "Swing" or "special". As soon as you have typed "sw" the program shows a possible completion "ing" highlighted in light-blue. Press Enter to take the completion or continue typing.

The following code adds a document listener to the text surface area's document:

            textArea.getDocument().addDocumentListener(this);          

When you started typing a word, the insertUpdate method checks whether the program'due south vocabulary contains the typed prefix. In one case a completion for the prefix is found, a call to the invokeLater method submits a chore for irresolute the certificate after. It is of import to remember that yous cannot change the certificate from within the document upshot notification, otherwise you will get an exception. Examine the following code beneath.

String prefix = content.substring(w + i).toLowerCase(); int n = Collections.binarySearch(words, prefix); if (n < 0 && -northward <= words.size()) {     String match = words.get(-due north - 1);     if (lucifer.startsWith(prefix)) {         // A completion is constitute         Cord completion = match.substring(pos - west);         // We cannot modify Certificate from within notification,         // so we submit a chore that does the change later         SwingUtilities.invokeLater(             new CompletionTask(completion, pos + one));     } } else {     // Nothing plant     mode = Way.INSERT; }          

The code shown in bold illustrates how the selection is created. The caret is first fix to the stop of the complete word, then moved dorsum to a position after the last character typed. The moveCaretPosition method non only moves the caret to a new position but also selects the text betwixt 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 Expanse API

The following tables list the usually used JTextArea constructors and methods. Other methods you lot are likely to phone call are defined in JTextComponent, and listed in The Text Component API.

You lot might also invoke methods on a text area that information technology inherits from its other ancestors, such as setPreferredSize, setForeground, setBackground, setFont, and so on. See The JComponent Grade for tables of commonly used inherited methods.

The API for using text areas includes the following categories:

  • Setting or Obtaining Contents
  • Fine Tuning Appearance
  • Implementing Functionality
Setting or Obtaining Contents
Method or Constructor Purpose
JTextArea()
JTextArea(String)
JTextArea(String, int, int)
JTextArea(int, int)
Creates a text area. When nowadays, the String argument contains the initial text. The int arguments specify the desired width in columns and pinnacle in rows, respectively.
void setText(String)
String getText()
(defined in JTextComponent)
Sets or obtains the text displayed past the text area.
Fine Tuning the Text Area'due south Appearance
Method Purpose
void setEditable(boolean)
boolean isEditable()
(divers in JTextComponent)
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 calculating the surface area'due south preferred width.
void setRows(int);
int getRows()
Sets or obtains the number of rows displayed past the text area. This is a hint for computing the area'south preferred superlative.
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. Past default this holding is false and lines are not wrapped.
int setWrapStyleWord(boolean) Sets whether lines tin can be wrapped at white infinite (word boundaries) or at any grapheme. By default this property is false, and lines can be wrapped (if line wrapping is turned on) at any character.
Implementing the Text Expanse's Functionality
Method Purpose
void selectAll()
(divers in JTextComponent)
Selects all characters in the text area.
void append(Cord) Adds the specified text to the end of the text expanse.
void insert(Cord, int) Inserts the specified text at the specified position.
void replaceRange(String, int, int) Replaces the text between the indicated positions with the specified cord.
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.

Examples That Utilise Text Areas

This table lists examples that use text areas and points to where those examples are described.

Instance Where Described Notes
TextDemo This department An application that appends user-entered text to a text area.
TextAreaDemo This section An application that has a text surface area with a give-and-take completion part.
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 blazon HTML code to be displayed in a label.
BasicDnD Introduction to DnD Demonstrates born 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 expanse.

jordanofer1984.blogspot.com

Source: https://docs.oracle.com/javase/tutorial/uiswing/components/textarea.html

0 Response to "How to Stop Reading Text in Java When It Gets to the End"

Post a Comment

Iklan Atas Artikel

Iklan Tengah Artikel 1

Iklan Tengah Artikel 2

Iklan Bawah Artikel