JTextField
The JTextField class allows the entry by the user of a piece of text in a box consisting of a single line:
private JPanel buildUI() {
JPanel panel = new JPanel(new BorderLayout());
// Components will go here...
JTextField field = new JTextField(25);
panel.add(field);
// Return the built panel
return panel;
}
- The value in the
JTextFieldconstructor specifies the number of character spaces for use as the length of the field, although this is for display purposes only, since the user will be able to type any number of characters
You can make the field show some initial default text by using the two-argument constructor:
JTextField field = new JTextField("Default text", 25);
Your frame should look like this:
Like the JLabel class, you can use methods setText() and getText() to change and obtain the text value in the entry box.
The JTextField class is frequently used in combination with the JLabel class to give the user an indication of what type of information is expected to be entered. You could add each of these to a left-aligned flow layout, for example:
JPanel namePanel = new JPanel(new FlowLayout(FlowLayout.LEFT));
namePanel.add(new JLabel("Enter your name:"));
JTextField field = new JTextField("Default text", 25);
namePanel.add(field);
panel.add(namePanel);
The frame should look as follows:
If you want the label above the text field instead of to its left, you could place them in a single-column grid:
JPanel namePanel = new JPanel(new GridLayout(2, 1));
namePanel.add(new JLabel("Enter your name:"));
JTextField field = new JTextField("Default text", 25);
namePanel.add(field);
panel.add(namePanel);
Which will look like this:
Comments