Java Program to set Horizontal Alignment of content in a JTextField

Java 8Object Oriented ProgrammingProgramming

The content in the JTextFile is by default left aligned, but you can change it using the setHorizontalAlignment() method. Let’s say the following is our JTextField −

JTextField emailId = new JTextField(20);

Now, we will set the horizontal alignment and set the alignment to the right for the JTextPane −

emailId.setHorizontalAlignment(JTextField.RIGHT);

The following is an example to set horizontal alignment of content in a JTextField −

package my;
import java.awt.FlowLayout;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JTextField;
import javax.swing.SwingConstants;
public class SwingDemo {
   public static void main(String[] args) throws Exception {
      JFrame frame = new JFrame("Demo");
      JLabel label;
      frame.setLayout(new FlowLayout());
      label = new JLabel("Email-Id : ", SwingConstants.LEFT);
      JTextField emailId = new JTextField(20);
      emailId.setHorizontalAlignment(JTextField.RIGHT);
      frame.add(label);
      frame.add(emailId);
      frame.setSize(550,250);
      frame.setVisible(true);
   }
}

Output

raja
Published on 04-Jun-2019 09:36:06
Advertisements