Modify horizontal alignment at runtime for JTextField in Java

Description

The following code shows how to modify horizontal alignment at runtime for JTextField.

Example


import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
/*from w w w  .ja  va  2s.c  o  m*/
import javax.swing.JFrame;
import javax.swing.JTextField;

public class Main {

  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();
  }
}

The code above generates the following result.

Modify horizontal alignment at runtime for JTextField in Java




















Home »
  Java Tutorial »
    Swing »




Action
Border
Color Chooser
Drag and Drop
Event
Font Chooser
JButton
JCheckBox
JComboBox
JDialog
JEditorPane
JFileChooser
JFormattedText
JFrame
JLabel
JList
JOptionPane
JPasswordField
JProgressBar
JRadioButton
JScrollBar
JScrollPane
JSeparator
JSlider
JSpinner
JSplitPane
JTabbedPane
JTable
JTextArea
JTextField
JTextPane
JToggleButton
JToolTip
JTree
Layout
Menu
Timer