Java Swing How to - Control Horizontal Alignment for JTextField








Question

We would like to know how to control Horizontal Alignment for JTextField.

Answer

//from w  ww .  j  a va  2  s  . c  o  m
/*
JTextField.LEFT
JTextField.CENTER
JTextField.RIGHT
JTextField.LEADING (the default), or
JTextField.TRAILING
*/
import java.awt.BorderLayout;
import java.awt.event.KeyEvent;

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

public class Main {
  public static void main(String args[]) {
    JPanel panel = new JPanel(new BorderLayout());
    JLabel label = new JLabel("Name: ");
    label.setDisplayedMnemonic(KeyEvent.VK_N);
    JTextField textField = new JTextField();
    textField.setHorizontalAlignment(JTextField.CENTER) ;
    
    label.setLabelFor(textField);
    panel.add(label, BorderLayout.WEST);
    panel.add(textField, BorderLayout.CENTER);

    
    JFrame frame = new JFrame();
    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

    frame.add(panel, BorderLayout.NORTH);
    frame.setSize(250, 150);
    frame.setVisible(true);

  }
}