Você está na página 1de 13

JTextField is a fundamental Swings component that allows users editing a single line of text.

This article lists

common practices when using JTextField in Swing development.


Table of content:
I.
1.

Creating a JTextField object

2.

Adding the text field to a container

3.

Getting or setting content of the text field

4.

Setting tooltip text

5.

Setting input focus

6.

Adding event listeners

7.

Working with text selection

8.

Customizing JTextFields appearance

9.

JTextField demo program

1. Creating a JTextField object


When creating a text field component, its common to specify some initial text and/or a number of columns from
which the fields width is calculated.

Create a text field with some initial text:


1 JTextField textField = new JTextField("This is a text");

Image:

Create a text field with a specified number of columns:


1 JTextField textField = new JTextField(20);

Image:

Create a text field with both initial text and number of columns:
1 JTextField textField = new JTextField("This is a text", 20);

Image:

Create a default and empty text field then set the text and the number of columns later:

1 JTextField textField = new JTextField();


2 textField.setText("This is a text");
3 textField.setColumns(20);
NOTE:

If the initial text is not specified, its default value is null (the text field is empty).

If the number of columns is not specified, its default value is 0 (then the text fields width is calculated
based on the initial text).

2. Adding the text field to a container

A JTextField can be added to any container like JFrame, JPanel, JDialog or JApplet:
1 frame.add(textField);
2 dialog.add(textField);
3 panel.add(textField);
4 applet.getContentPane().add(textField);

Add a JTextField to the container with a specific layout manager:

1 frame.add(textField, BorderLayout.CENTER);
2 panel.add(textField, gridbagConstraints);

3. Getting or setting content of the text field

Getting all content:

1 String content = textField.getText();

Getting a portion of the content:


1 int offset = 5;
2 int length = 10;
3
4 try {
5

content = textField.getText(offset, length);

6 } catch (BadLocationException ex) {


// invalid offset/length

7
8

That will return 10 characters from position 5th in the text.

Setting content:

1 textField.setText("another text");

4. Setting tooltip text


Set tooltip for the text field as follows:
1 textField.setToolTipText("Please enter some text here");

Image:

We can also set HTML for the tooltip text:


1 textField.setToolTipText("<html><b><font color=red>"

2
+ "Please enter some text here" + "</font></b></html>");

Image:

5. Setting input focus


Normally, the text field gets focused when the user is clicking on it or pressing the TAB key. To set input focus programmatically, use
the following code:

Setting input focus initially just after the container (such as a JFrame) is displayed:
1 frame.setVisible(true);
2 textField.requestFocusInWindow();

Setting input focus at any time: Its recommend to request the focus inside a SwingUtilities.invokeLater()
call:

1 SwingUtilities.invokeLater(new Runnable() {
2

@Override

public void run() {

textField.requestFocusInWindow();

6 });

6. Adding event listeners

We can capture the event in which the user hits Enter key while typing in the text field. For example:
1 textField.addActionListener(new ActionListener() {
2

@Override

public void actionPerformed(ActionEvent event) {


System.out.println("The entered text is: " + textField.getText());

4
5

6 });

1
2

Capture key events which happen while the user is typing into the text field:
textField.addKeyListener(new KeyListener() {

@Override

public void keyTyped(KeyEvent event) {

System.out.println("key typed");

7
8

@Override

public void keyReleased(KeyEvent event) {

10

System.out.println("key released");
}

11
12
13

@Override

14

public void keyPressed(KeyEvent event) {


System.out.println("key pressed");

15
}

16
17

});

The order of key events is key pressed, key typed and key released. We can use this technique to validate fields content on-thefly. In the following example, we check the fields content whenever the user is typing. If the content is empty, disable the action
button; otherwise enable the button:

1
2

textField.addKeyListener(new KeyAdapter() {
public void keyReleased(KeyEvent event) {

3
4

String content = textField.getText();

if (!content.equals("")) {

button.setEnabled(true);

} else {
button.setEnabled(false);

8
}

9
10
11

}
});<br><br>

NOTE: In this case, we use the KeyAdapter class which implements the KeyListener interface, so we have to override
only the method we want.
1

Related Course: Java Swing (GUI) Programming: From Beginner to Expert

7. Working with text selection


We can programmatically select the text fields content.

Select all text:


1

textField.selectAll();

Image:

Select only a portion of text:


1

textField.setSelectionStart(8);

textField.setSelectionEnd(12);

Image:

Set color for the selection and the selected text:


1 textField.setSelectionColor(Color.YELLOW);
2 textField.setSelectedTextColor(Color.RED);

Image:

Set position of the caret and its color:

1 textField.setCaretColor(Color.RED);
2 textField.setCaretPosition(10);

Image:

8. Customizing JTextFields appearance

Disable editing the fields content:


1

textField.setEditable(false);

Image:

Set horizontal alignment of text:


1 textField.setHorizontalAlignment(JTextField.CENTER);

Image:
Valid values for the method setHorizontalAlignment() are:
1

JTextField.LEFT

JTextField.CENTER

JTextField.RIGHT

JTextField.LEADING

JTextField.TRAILING

Set font style, background color and foreground color:

1 textField.setFont(new java.awt.Font("Arial", Font.ITALIC | Font.BOLD, 12));


2 textField.setForeground(Color.BLUE);
3 textField.setBackground(Color.YELLOW);

Image:
Learn Advanced Swing techniques in Core Java, Volume II--Advanced Features (9th Edition)

9. JTextField demo program


For your reference and testing purpose, we created a simple demo program looks like this:

When you are typing something in the text field and hit Enter, the following message dialog appears:

If the field is empty, the OK button is disabled:

And when clicking the button:

Você também pode gostar