The JTextField Class

JTextField allows the user to enter a single line of text, scrolling the text if its size exceeds the physical size of the field. A JTextField fires an ActionEvent to any registered ActionListeners (including the Action set via the setAction( ) method, if any) when the user presses the Enter key.

JTextFields (and all JTextComponents) are automatically installed with a number of behaviors appropriate to the L&F, so cut/copy/paste, special cursor movement keys, and text-selection gestures should work without any extra intervention on your part.

The following program presents a JTextField for the user to edit (shown in Figure 19-3). The JTextField is initially right-justified, but the justification changes each time the Enter key is pressed.

// JTextFieldExample.java // import javax.swing.*; import java.awt.event.*; public class JTextFieldExample { public static void main(String[] args) { final JTextField tf = new JTextField("press <enter>", 20); tf.setHorizontalAlignment(JTextField.RIGHT); tf.addActionListener(new ActionListener( ) { public void actionPerformed(ActionEvent e) { int old = tf.getHorizontalAlignment( ); if (old == JTextField.LEFT) tf.setHorizontalAlignment(JTextField.RIGHT); if (old == JTextField.RIGHT) tf.setHorizontalAlignment(JTextField.CENTER); if (old == JTextField.CENTER) tf.setHorizontalAlignment(JTextField.LEFT); } }); JFrame frame = new JFrame("JTextFieldExample"); frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); frame.getContentPane( ...

Get Java Swing, 2nd Edition now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.