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.
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().setLayout(new java.awt.FlowLayout()); frame.getContentPane().add(tf); frame.setSize(275, 75); frame.setVisible(true); tf.requestFocus(); } }