Escolar Documentos
Profissional Documentos
Cultura Documentos
2.
3.
4.
5.
6.
7.
8.
9.
Image:
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:
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).
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);
1 frame.add(textField, BorderLayout.CENTER);
2 panel.add(textField, gridbagConstraints);
7
8
Setting content:
1 textField.setText("another text");
Image:
2
+ "Please enter some text here" + "</font></b></html>");
Image:
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
textField.requestFocusInWindow();
6 });
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
4
5
6 });
1
2
Capture key events which happen while the user is typing into the text field:
textField.addKeyListener(new KeyListener() {
@Override
System.out.println("key typed");
7
8
@Override
10
System.out.println("key released");
}
11
12
13
@Override
14
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
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
textField.selectAll();
Image:
textField.setSelectionStart(8);
textField.setSelectionEnd(12);
Image:
Image:
1 textField.setCaretColor(Color.RED);
2 textField.setCaretPosition(10);
Image:
textField.setEditable(false);
Image:
Image:
Valid values for the method setHorizontalAlignment() are:
1
JTextField.LEFT
JTextField.CENTER
JTextField.RIGHT
JTextField.LEADING
JTextField.TRAILING
Image:
Learn Advanced Swing techniques in Core Java, Volume II--Advanced Features (9th Edition)
When you are typing something in the text field and hit Enter, the following message dialog appears: