Swing Text Components: Text Fields, Labels, Password Fields and Text Areas
Collecting text input in Swing: JTextField, labels and accessible labeling, JPasswordField with char arrays, JTextArea with wrapping, and scroll panes, plus document listeners, filters that restrict input, and undo.
kvi5hnuCode Sprout team member13 min readOn this page
The first real components to learn are the ones that take text from the user. Swing has three for plain input: JTextField for one line, JPasswordField for one line that is not displayed, and JTextArea for several lines. Labels identify them, and scroll panes add scroll bars. Behind all of them sits a Document, the model from the previous article; once you know it, validating input, reacting to every keystroke and adding undo all become short.

All text components extend the abstract class JTextComponent. Many methods you look for are defined there rather than in the concrete classes, so check the superclass documentation too. The most important ones:
getText()andsetText(text)read and replace the whole content;setEditable(false)makes the component read-only (the user can still select and copy);getSelectedText(),select(start, end),replaceSelection(text),getCaretPosition()andsetCaretPosition(pos)work with the selection and the insertion point;getDocument()returns the model.
Text fields
Add a text field to a container like any component:
var panel = new JPanel();
var nameField = new JTextField("Default input", 20);
panel.add(nameField);
The second argument is the width in columns. A column is the expected width of one character in the field's font, a rough measure: proportional fonts make "iii" narrow and "WWW" wide. Add one or two columns to the longest expected input. The column count only sets the preferred size; a layout manager may make the field wider or narrower, and the user can type far more characters than there are columns (the text scrolls). Users dislike scrolling fields, so be generous.
To start with an empty field, use new JTextField(20). To change the width later, call setColumns and then revalidate() on the surrounding container, so that the layout manager recomputes sizes. revalidate only marks the component; the layout is redone once, later, on the event dispatch thread, even if many components changed. (For a whole frame, frame.revalidate() works too, since Java 7 defined revalidate in Component; validate() redoes the layout immediately.)
Read the input with getText(). It returns exactly what was typed, so trim spaces with getText().strip() when they are not meaningful. Change the font with setFont.
When the user presses Enter in a text field, the field fires an action event, so addActionListener on a field is a simple way to react to "input finished". For a form, a better choice is a default button: frame.getRootPane().setDefaultButton(okButton) makes Enter in any field press that button. Note that a field with its own action listener handles Enter itself, so the default button is not pressed from that field.
Reacting to every change
To react while the user types (to count characters, enable a button, or validate as they go), listen to the document, not to keys. Keys miss pasted text, drag and drop, and changes made by setText. A DocumentListener has three methods:
field.getDocument().addDocumentListener(new DocumentListener() {
public void insertUpdate(DocumentEvent e) { update(); }
public void removeUpdate(DocumentEvent e) { update(); }
public void changedUpdate(DocumentEvent e) { } // style changes; never fired by plain documents
});
The event tells you the offset and length of the change. Note that setText is a removal followed by an insertion, as the demo's log shows. Also note that you must not modify the document inside a document listener; that throws an IllegalStateException. To change or reject input, use a filter instead.
Restricting input with a DocumentFilter
A DocumentFilter sits between the editing operations and the document. Every insertion and replacement passes through it, whatever its origin: typing, pasting or setText. The filter can pass the text on unchanged, modify it, or drop it:
((AbstractDocument) field.getDocument()).setDocumentFilter(new DocumentFilter() {
@Override
public void replace(FilterBypass fb, int offset, int length, String text, AttributeSet attrs)
throws BadLocationException {
fb.replace(offset, length, text.toUpperCase(), attrs); // force upper case
}
});
Override insertString, replace and (if needed) remove. The demo's filter accepts only digits and limits the length, the usual way to build a postal code or PIN field. Checking the complete value (is this a valid date?) is a different job: do it when the user submits, or use the JFormattedTextField subclass, which converts between text and a value with a Format and can refuse invalid input when the field loses focus. An InputVerifier (setInputVerifier) can also keep the focus in a field until its content is valid, though users often find that heavy-handed.
Undo
Documents report every edit to UndoableEditListeners. The UndoManager class collects them, so adding undo and redo takes three lines:
var undo = new UndoManager();
textArea.getDocument().addUndoableEditListener(undo);
// in the actions for Ctrl+Z and Ctrl+Y:
if (undo.canUndo()) undo.undo();
if (undo.canRedo()) undo.redo();
Article 96 shows how to bind such actions to menu items and keys.
Labels and labeling components
A JLabel displays text, an icon, or both. It has no border and does not react to input. Text fields, unlike buttons, carry no text of their own, so you place a label next to each one. The constructor optionally takes an alignment from the SwingConstants interface (LEFT, CENTER, RIGHT, LEADING, TRAILING):
var label = new JLabel("User name: ", SwingConstants.RIGHT);
Because JLabel implements SwingConstants, JLabel.RIGHT works too. setText and setIcon change the label at run time.
Labels (and buttons and menu items) accept simple HTML when the text starts with <html>:
var label = new JLabel("<html><b>Required</b> entry:</html>");
HTML in labels is handy for bold words, line breaks (<br>) and colored text; avoid it in buttons, where it conflicts with the look and feel. The first HTML label loads the HTML rendering code, which takes a moment. Be careful with text you did not write: a label that shows user input or data from a file would interpret any <html> prefix in it. Call putClientProperty("html.disable", Boolean.TRUE) on such labels.
Connecting a label to its field
Placing a label near a field is enough for sighted users, but not for screen readers or keyboard users. Connect the two:
label.setLabelFor(nameField);
label.setDisplayedMnemonic('N');
Now Alt+N (Ctrl+Option+N on macOS) moves the focus to the field, the label underlines the "n" in "name", and assistive technology announces the field by the label's text. The demo confirms that the field's accessible name became "User name: ". This costs two lines per field and should be routine.
Password fields
A JPasswordField is a text field that displays an echo character (a bullet in the default look and feel) for each typed character. It is a nice example of MVC: the model is the same PlainDocument as in an ordinary field, and only the view differs.
var passwordField = new JPasswordField(20);
char[] password = passwordField.getPassword();
try {
// check the password
} finally {
Arrays.fill(password, '\0');
}
getPassword returns a char[], not a String, so you can overwrite the characters once you are done; a string would stay in memory until garbage collection and might show up in a heap dump. The inherited getText is deprecated in this class for that reason. (This protection is limited: the document itself still holds the characters while the field exists, so clear the field after use as well.) To check the password, compare against a salted hash, as described in Article 83.
setEchoChar(c) chooses a different echo character, which a look and feel may ignore; setEchoChar((char) 0) shows the text in clear, the usual implementation of a "show password" check box. Text components also normally support copy and cut; password fields disable both.
Text areas
A JTextArea accepts any number of lines; the user separates them with Enter. The constructor takes the preferred number of rows and columns:
var textArea = new JTextArea(8, 40); // 8 lines of 40 columns
As with fields, these are size hints, adjustable with setRows and setColumns; the user is not limited to them. Lines in the document always end in a single '\n', on every platform. (When the component reads a file with read(reader, desc), the editor kit converts \r\n to \n and remembers the original separator for write; setText stores exactly what you give it, so normalize line ends yourself if text comes from elsewhere.)
Text that is too long for a line is cut off at the edge. Turn on wrapping to avoid that:
textArea.setLineWrap(true); // wrap long lines
textArea.setWrapStyleWord(true); // ...at word boundaries rather than anywhere
Wrapping is purely visual: no newlines are inserted into the text, and getLineCount still counts the real lines. Other useful methods are append(text), insert(text, pos), replaceRange(text, start, end), setTabSize(n) (tab stops every n columns; tabs stay tab characters), and getLineOfOffset, getLineStartOffset and getLineEndOffset, which convert between character offsets and line numbers, for example to show "line 12, column 5" in a status bar.
A JTextArea displays plain text in one font. For formatted text, JEditorPane displays HTML 3.2 and RTF, and JTextPane supports styled text with fonts, colors and embedded components.
Scroll panes
Swing text areas have no scroll bars. To get them, put the area into a JScrollPane and add the scroll pane to the container:
var textArea = new JTextArea(8, 40);
frame.add(new JScrollPane(textArea), BorderLayout.CENTER);
The scroll pane shows the area through a viewport. Scroll bars appear when the content is larger than the viewport and disappear when it fits again; your program does not handle any scroll events. This works for any component, not only text areas: lists, tables, trees, or a large drawing panel. Components that implement the Scrollable interface (text components, lists, tables, trees) also tell the scroll pane how far one click on a scroll arrow should move. To change when scroll bars are shown, use setVerticalScrollBarPolicy and setHorizontalScrollBarPolicy with the constants of ScrollPaneConstants (..._AS_NEEDED, ..._ALWAYS, ..._NEVER).
A sign-in window
The following program combines the components of this article. A two-by-two grid holds the labeled user name and password fields; a text area in a scroll pane logs each attempt; a document listener enables the button only when both fields are filled in; Enter presses the default button; and a check box shows the password. The password array is wiped after use.
import java.awt.*;
import java.util.Arrays;
import javax.swing.*;
import javax.swing.event.DocumentEvent;
import javax.swing.event.DocumentListener;
public final class SignInFrame extends JFrame {
private static final long serialVersionUID = 1L;
private final JTextField userField = new JTextField(16);
private final JPasswordField passwordField = new JPasswordField(16);
private final JTextArea log = new JTextArea(8, 30);
private final JLabel status = new JLabel(" ");
public SignInFrame() {
super("Sign in");
var userLabel = new JLabel("User name: ", SwingConstants.RIGHT);
userLabel.setLabelFor(userField);
userLabel.setDisplayedMnemonic('U');
var passwordLabel = new JLabel("Password: ", SwingConstants.RIGHT);
passwordLabel.setLabelFor(passwordField);
passwordLabel.setDisplayedMnemonic('P');
var form = new JPanel(new GridLayout(2, 2, 4, 4));
form.add(userLabel);
form.add(userField);
form.add(passwordLabel);
form.add(passwordField);
add(form, BorderLayout.NORTH);
log.setEditable(false);
log.setLineWrap(true);
log.setWrapStyleWord(true);
add(new JScrollPane(log), BorderLayout.CENTER);
var signIn = new JButton("Sign in");
signIn.addActionListener(_ -> signIn());
getRootPane().setDefaultButton(signIn); // Enter in either field presses it
var show = new JCheckBox("Show password");
char defaultEcho = passwordField.getEchoChar();
show.addActionListener(_ -> passwordField.setEchoChar(show.isSelected() ? 0 : defaultEcho));
var south = new JPanel(new BorderLayout());
var buttons = new JPanel();
buttons.add(show);
buttons.add(signIn);
south.add(buttons, BorderLayout.NORTH);
south.add(status, BorderLayout.SOUTH);
add(south, BorderLayout.SOUTH);
// enable the button only when both fields have content
DocumentListener validator = new DocumentListener() {
public void insertUpdate(DocumentEvent e) { update(); }
public void removeUpdate(DocumentEvent e) { update(); }
public void changedUpdate(DocumentEvent e) { }
private void update() {
signIn.setEnabled(!userField.getText().isBlank()
&& passwordField.getDocument().getLength() > 0);
}
};
userField.getDocument().addDocumentListener(validator);
passwordField.getDocument().addDocumentListener(validator);
signIn.setEnabled(false);
pack();
setDefaultCloseOperation(EXIT_ON_CLOSE);
setLocationByPlatform(true);
}
private void signIn() {
String user = userField.getText().strip();
char[] password = passwordField.getPassword();
try {
// a real program would check a salted hash here (see the security part)
log.append("Sign-in attempt for " + user + " with a "
+ password.length + "-character password\n");
status.setText("Last attempt: " + user);
} finally {
Arrays.fill(password, '\0');
passwordField.setText("");
}
}
public static void main(String[] args) {
EventQueue.invokeLater(() -> new SignInFrame().setVisible(true));
}
}
The program
The demo creates text components without showing them and drives them from code, which works in headless mode. It reads and changes text and selections, logs document events, undoes an edit, filters input, checks a password safely, connects a label to a field, and examines lines in a text area and the parts of a scroll pane.
import java.awt.GridLayout;
import java.util.Arrays;
import java.util.ArrayList;
import java.util.List;
import javax.swing.*;
import javax.swing.event.DocumentEvent;
import javax.swing.event.DocumentListener;
import javax.swing.plaf.basic.BasicHTML;
import javax.swing.text.*;
import javax.swing.undo.UndoManager;
public class Solution {
public static void main(String[] args) throws Exception {
System.setProperty("java.awt.headless", "true");
SwingUtilities.invokeAndWait(Solution::run);
}
static void run() {
try {
textFields();
documentEvents();
filters();
passwords();
labels();
textAreas();
scrollPanes();
} catch (BadLocationException e) {
throw new IllegalStateException(e);
}
}
static void textFields() {
System.out.println("== JTextField ==");
var field = new JTextField("Default input", 20);
System.out.println("columns = " + field.getColumns() + ", text = \"" + field.getText() + "\"");
field.setText(" a value typed with spaces ");
System.out.println("getText() = \"" + field.getText() + "\"");
System.out.println("getText().strip() = \"" + field.getText().strip() + "\"");
field.setColumns(5);
field.setText("columns are a size hint, not a limit on the input");
System.out.println("5 columns, length " + field.getText().length() + " accepted");
System.out.println("document class: " + field.getDocument().getClass().getSimpleName());
System.out.println("editable = " + field.isEditable());
// selection and caret, as a user would produce with the mouse
field.setText("Hello, world");
field.select(7, 12);
System.out.println("selected = \"" + field.getSelectedText() + "\"");
field.replaceSelection("Swing");
System.out.println("after replaceSelection: \"" + field.getText() + "\", caret at " + field.getCaretPosition());
}
static void documentEvents() throws BadLocationException {
System.out.println();
System.out.println("== DocumentListener sees every change ==");
var field = new JTextField(10);
List<String> log = new ArrayList<>();
field.getDocument().addDocumentListener(new DocumentListener() {
public void insertUpdate(DocumentEvent e) { log.add("insert " + e.getLength() + " at " + e.getOffset()); }
public void removeUpdate(DocumentEvent e) { log.add("remove " + e.getLength() + " at " + e.getOffset()); }
public void changedUpdate(DocumentEvent e) { log.add("attributes changed"); }
});
field.setText("abc"); // insert
field.getDocument().insertString(3, "def", null);
field.setText("xy"); // remove all, then insert
field.getDocument().remove(0, 1);
log.forEach(s -> System.out.println(" " + s));
System.out.println("text = \"" + field.getText() + "\"");
var undo = new UndoManager();
var area = new JTextArea();
area.getDocument().addUndoableEditListener(undo);
area.append("one ");
area.append("two ");
area.append("three");
undo.undo();
System.out.println("after one undo: \"" + area.getText() + "\"");
undo.redo();
System.out.println("after redo: \"" + area.getText() + "\"");
}
/** Accepts only digits and at most max characters. */
static class DigitsFilter extends DocumentFilter {
private final int max;
DigitsFilter(int max) { this.max = max; }
@Override
public void insertString(FilterBypass fb, int offset, String s, AttributeSet a)
throws BadLocationException {
replace(fb, offset, 0, s, a);
}
@Override
public void replace(FilterBypass fb, int offset, int length, String s, AttributeSet a)
throws BadLocationException {
String digits = s == null ? "" : s.replaceAll("\\D", "");
int room = max - (fb.getDocument().getLength() - length);
if (digits.length() > room) digits = digits.substring(0, Math.max(room, 0));
fb.replace(offset, length, digits, a);
}
}
static void filters() {
System.out.println();
System.out.println("== DocumentFilter: digits only, at most 6 ==");
var zip = new JTextField(8);
((AbstractDocument) zip.getDocument()).setDocumentFilter(new DigitsFilter(6));
zip.setText("56-0001");
System.out.println("setText(\"56-0001\") -> \"" + zip.getText() + "\"");
zip.setCaretPosition(zip.getText().length());
zip.replaceSelection("789");
System.out.println("typing 789 at end -> \"" + zip.getText() + "\"");
}
static void passwords() {
System.out.println();
System.out.println("== JPasswordField ==");
var password = new JPasswordField("s3cret", 12);
System.out.println("echo char = U+" + String.format("%04X", (int) password.getEchoChar()));
System.out.println("same model type as a text field: "
+ password.getDocument().getClass().getSimpleName());
char[] chars = password.getPassword();
System.out.println("getPassword() -> char[" + chars.length + "]");
boolean ok = Arrays.equals(chars, "s3cret".toCharArray());
Arrays.fill(chars, '\0'); // wipe the copy after use
System.out.println("matches = " + ok + ", array wiped = " + new String(chars).chars().allMatch(c -> c == 0));
password.setEchoChar((char) 0); // show the text (a "show password" option)
System.out.println("echoing after setEchoChar(0): " + password.echoCharIsSet());
}
static void labels() {
System.out.println();
System.out.println("== JLabel ==");
var right = new JLabel("User name: ", SwingConstants.RIGHT);
System.out.println("alignment RIGHT? " + (right.getHorizontalAlignment() == SwingConstants.RIGHT));
var html = new JLabel("<html><b>Required</b> entry:</html>");
System.out.println("HTML text recognized: " + BasicHTML.isHTMLString(html.getText())
+ ", renderer installed: " + (html.getClientProperty(BasicHTML.propertyKey) != null));
var plain = new JLabel("Plain");
System.out.println("plain label renderer: " + (plain.getClientProperty(BasicHTML.propertyKey) != null));
var nameField = new JTextField(15);
right.setLabelFor(nameField);
right.setDisplayedMnemonic('N');
System.out.println("label is for a " + right.getLabelFor().getClass().getSimpleName()
+ ", mnemonic " + keyName(right.getDisplayedMnemonic())
+ ", underlined index " + right.getDisplayedMnemonicIndex());
System.out.println("accessible name of field: "
+ nameField.getAccessibleContext().getAccessibleName());
var form = new JPanel(new GridLayout(2, 2));
form.add(right);
form.add(nameField);
form.add(new JLabel("Password: ", SwingConstants.RIGHT));
form.add(new JPasswordField(15));
System.out.println("form panel has " + form.getComponentCount() + " components in a "
+ ((GridLayout) form.getLayout()).getRows() + "x" + ((GridLayout) form.getLayout()).getColumns() + " grid");
}
static String keyName(int code) {
return java.awt.event.KeyEvent.getKeyText(code);
}
static void textAreas() throws BadLocationException {
System.out.println();
System.out.println("== JTextArea ==");
var area = new JTextArea(8, 40);
System.out.println("rows = " + area.getRows() + ", columns = " + area.getColumns());
area.append("first line\n");
area.append("second line\n");
area.append("a third line that is much longer than forty columns of text");
System.out.println("line count = " + area.getLineCount());
for (int i = 0; i < area.getLineCount(); i++) {
int start = area.getLineStartOffset(i), end = area.getLineEndOffset(i);
System.out.printf(" line %d: offsets %2d..%2d \"%s\"%n", i, start, end,
area.getText(start, end - start).replace("\n", "\\n"));
}
System.out.println("offset 30 is on line " + area.getLineOfOffset(30));
area.setLineWrap(true);
area.setWrapStyleWord(true);
System.out.println("wrapping on; line count still " + area.getLineCount()
+ " (wrapping is only visual)");
area.insert(">> ", 0);
area.replaceRange("2nd", area.getLineStartOffset(1), area.getLineStartOffset(1) + 6);
System.out.println("after insert and replaceRange:");
for (String line : area.getText().split("\n")) System.out.println(" " + line);
area.setTabSize(4);
System.out.println("tab size = " + area.getTabSize());
area.setText("pasted\r\ntext");
System.out.println("setText keeps \\r\\n as-is: "
+ area.getText().contains("\r") + " (only the editor kit's read() normalizes line ends)");
}
static void scrollPanes() {
System.out.println();
System.out.println("== JScrollPane ==");
var area = new JTextArea(8, 40);
var scroll = new JScrollPane(area);
System.out.println("viewport view is the area: " + (scroll.getViewport().getView() == area));
System.out.println("vertical policy as needed: "
+ (scroll.getVerticalScrollBarPolicy() == ScrollPaneConstants.VERTICAL_SCROLLBAR_AS_NEEDED));
scroll.setHorizontalScrollBarPolicy(ScrollPaneConstants.HORIZONTAL_SCROLLBAR_NEVER);
System.out.println("horizontal policy never: "
+ (scroll.getHorizontalScrollBarPolicy() == ScrollPaneConstants.HORIZONTAL_SCROLLBAR_NEVER));
System.out.println("area implements Scrollable: " + (area instanceof Scrollable));
}
}
== JTextField ==
columns = 20, text = "Default input"
getText() = " a value typed with spaces "
getText().strip() = "a value typed with spaces"
5 columns, length 49 accepted
document class: PlainDocument
editable = true
selected = "world"
after replaceSelection: "Hello, Swing", caret at 12
== DocumentListener sees every change ==
insert 3 at 0
insert 3 at 3
remove 6 at 0
insert 2 at 0
remove 1 at 0
text = "y"
after one undo: "one two "
after redo: "one two three"
== DocumentFilter: digits only, at most 6 ==
setText("56-0001") -> "560001"
typing 789 at end -> "560001"
== JPasswordField ==
echo char = U+2022
same model type as a text field: PlainDocument
getPassword() -> char[6]
matches = true, array wiped = true
echoing after setEchoChar(0): false
== JLabel ==
alignment RIGHT? true
HTML text recognized: true, renderer installed: true
plain label renderer: false
label is for a JTextField, mnemonic N, underlined index 5
accessible name of field: User name:
form panel has 4 components in a 2x2 grid
== JTextArea ==
rows = 8, columns = 40
line count = 3
line 0: offsets 0..11 "first line\n"
line 1: offsets 11..23 "second line\n"
line 2: offsets 23..82 "a third line that is much longer than forty columns of text"
offset 30 is on line 2
wrapping on; line count still 3 (wrapping is only visual)
after insert and replaceRange:
>> first line
2nd line
a third line that is much longer than forty columns of text
tab size = 4
setText keeps \r\n as-is: true (only the editor kit's read() normalizes line ends)
== JScrollPane ==
viewport view is the area: true
vertical policy as needed: true
horizontal policy never: true
area implements Scrollable: true
Points to notice:
- A field with 5 columns accepted 49 characters; the column count affects only the preferred size.
setText("xy")produced two events: removal of the six old characters, then insertion of the two new ones.- The filter turned
"56-0001"into"560001"and then rejected further digits, because the field was full. It applies tosetTextas well as to typing. - The label's mnemonic was underlined at index 5, the first "n" in "User name: ", ignoring case; and the field took its accessible name from the label.
- Turning on line wrapping did not change the line count: the document still has three lines.
Common questions
How do I allow only numbers in a text field?
Install a DocumentFilter that rejects non-digits (as in the demo), or use a JFormattedTextField with a NumberFormatter, or a JSpinner with a SpinnerNumberModel for bounded numbers. Validate the complete value again when the form is submitted.
How do I add placeholder ("hint") text to a field?
Swing has no built-in property for it. FlatLaf supports putClientProperty("JTextField.placeholderText", "Search"). Otherwise, override paintComponent to draw a gray hint when the text is empty and the field has no focus.
Why does setText in a DocumentListener throw IllegalStateException?
You can't modify a document while it notifies listeners. Defer the change with SwingUtilities.invokeLater, or move the logic into a DocumentFilter, which is designed for changing input.
How do I make a text area scroll to the bottom as I append?
Call area.setCaretPosition(area.getDocument().getLength()) after append, or set the caret's update policy: ((DefaultCaret) area.getCaret()).setUpdatePolicy(DefaultCaret.ALWAYS_UPDATE).
Why is getText() on a password field deprecated?
It returns a String, which can't be wiped from memory. Use getPassword() and clear the array with Arrays.fill(chars, '\0') after use.
API reference
| Class / method | Purpose |
|---|---|
JTextComponent.getText, setText, isEditable, setEditable, getDocument | Content and model. |
JTextComponent.select, getSelectedText, replaceSelection, getCaretPosition, setCaretPosition | Selection and caret. |
JTextField(columns), JTextField(text, columns), getColumns, setColumns, addActionListener | Single-line field; Enter fires an action. |
JComponent.revalidate(), Component.validate(), setFont | Recompute layout; change font. |
Document.addDocumentListener, DocumentListener.insertUpdate/removeUpdate/changedUpdate | Observe every change. |
AbstractDocument.setDocumentFilter, DocumentFilter.insertString/replace/remove, FilterBypass | Modify or reject edits. |
Document.addUndoableEditListener, UndoManager.undo/redo/canUndo/canRedo | Undo support. |
JLabel(text, align), JLabel(text, icon, align), setText, setIcon, setLabelFor, setDisplayedMnemonic | Labels and labeling. |
JPasswordField(text, columns), getPassword, setEchoChar, echoCharIsSet | Password input. |
JTextArea(rows, columns), append, insert, replaceRange, setLineWrap, setWrapStyleWord, setTabSize, getLineCount, getLineOfOffset, getLineStartOffset | Multi-line text. |
JScrollPane(component), getViewport, setVerticalScrollBarPolicy, setHorizontalScrollBarPolicy | Scrolling. |
JRootPane.setDefaultButton | Button pressed by Enter. |
Summary
JTextField,JPasswordFieldandJTextAreaextendJTextComponent, which provides text, selection and editability methods. Column and row counts are only preferred sizes.- The text lives in a
Document. Listen to it with aDocumentListenerto react to every change; restrict input with aDocumentFilter; add undo with anUndoManager. - Label fields with
JLabel, and connect them withsetLabelForand a mnemonic for keyboard and screen-reader users. Disable HTML for labels that show untrusted text. - Read passwords with
getPasswordinto achar[], wipe it after use, and check against a salted hash. - Text areas wrap only visually. Files read with
read()get\nline ends, butsetTextstores text unchanged, so normalize line ends yourself. Put them, and any large component, into aJScrollPaneto get scroll bars.
Practice Questions
1. A text field is created with new JTextField(10). Can the user enter 30 characters?
Yes. The column count only determines the preferred width, computed as the number of columns times the width of the letter 'm' in the field's font. The user can type any number of characters; the text scrolls horizontally when it is longer than the visible part. To limit the length, install a DocumentFilter.
2. Why does JPasswordField.getPassword return a char[] rather than a String?
A String is immutable, so its characters stay in memory until the garbage collector reclaims it, possibly long after use and visible in a heap dump. A char[] can be overwritten with Arrays.fill(password, '\0') as soon as the password has been checked. The protection is partial, because the field's document also holds the characters, so clear the field too.
3. You want a "Save" button to be enabled only when a text field is not empty. Why is a KeyListener on the field the wrong tool, and what should you use?
Key events miss changes that do not come from typed keys: pasting with the mouse or a menu, drag and drop, and programmatic setText calls. Key events also arrive before the text changes. A DocumentListener on the field's document is told about every insertion and removal after it happens, so it can enable or disable the button reliably.
4. After setLineWrap(true), a 200-character line is displayed as four lines. What does getLineCount() return for that text, and what does getText() contain?
getLineCount() returns 1, and getText() returns the original 200 characters without any added newline. Wrapping only changes how the view draws the text; the document is unchanged.
5. A text area in the center of a BorderLayout shows no scroll bars even when the text is far longer than the window. What is missing?
Swing text areas have no scroll bars of their own. Wrap the area in a scroll pane and add the scroll pane instead: frame.add(new JScrollPane(textArea), BorderLayout.CENTER). The scroll pane shows scroll bars only when they are needed.
Previous: Swing Layout Managers and MVC: FlowLayout, BorderLayout and GridLayout
Next: Swing Choice Components: Check Boxes, Radio Buttons, Borders, Combo Boxes and Sliders
Related reading

More in Core Java II
FFM Upcalls, Variadic Functions and errno
Advanced FFM calls: passing Java code to C as function pointers with upcall stubs, binding objects and lambdas, calling variadic functions such as printf, capturing errno and GetLastError, and a C library that calls back into Java. The final article of the course.
Calling Foreign Functions: Linker, Symbol Lookup, Downcalls and jextract
Calling C functions from pure Java with the FFM API: the native linker, default, library and loader symbol lookups, function descriptors, downcall handles, invokeExact, pointers and NULL, struct results, critical calls, enabling native access, and generating bindings with jextract.
FFM Memory Layouts: Structs, Unions, Sequences and Var Handles
Describing C data with FFM memory layouts: value layouts and C types, struct and union layouts, alignment and padding, sequences, layout paths, var handles with base offsets, offset and slice handles, pointers with target layouts, and atomic access modes.
Foreign Function and Memory API: Arenas and Memory Segments
Getting started with the FFM API (final since Java 22): a first foreign call, confined, shared, automatic and global arenas, native and heap memory segments, reading and writing values, C strings and arrays, alignment and byte order, slices, copies, allocators, and memory-mapped files.
Discussion
Sign in to ask a question or share what you learned.