Java JTextField get/set horizontal text alignment

Description

Java JTextField get/set horizontal text alignment

import java.awt.FlowLayout;

import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JTextField;

public class Main extends JFrame {
  public Main() {
    super("JButton");

    setDefaultCloseOperation(EXIT_ON_CLOSE);
    setLayout(new FlowLayout());
    JLabel nameLabel = new JLabel("Name:");
    JTextField name = new JTextField(20);

    name.setHorizontalAlignment(JTextField.RIGHT);

    int horizontalAlignment = name.getHorizontalAlignment();

    switch (horizontalAlignment) {

    case JTextField.LEFT:
      name.setText("Left");
      break;/*from   w  w  w.j a v  a 2 s. c om*/
    case JTextField.RIGHT:
      name.setText("Right");
      break;
    case JTextField.CENTER:
      name.setText("Center");
      break;
    case JTextField.LEADING:
      name.setText("Leading");
      break;
    case JTextField.TRAILING:
      name.setText("Trailing");
      break;
    }

    getContentPane().add(nameLabel);
    getContentPane().add(name);

  }

  public static void main(String[] args) {
    Main frame = new Main();
    frame.pack();
    frame.setVisible(true);
  }
}



PreviousNext

Related