O'Reilly logo

Java Swing, 2nd Edition by Brian Cole, James Elliott, Marc Loy, Robert Eckstein, Dave Wood

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

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( ...

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required