Java program to set horizontal alignment of content in a JTextField



In this article, we will learn how to set the horizontal alignment of content in a JTextField class using Java Swing. The content in the JTextFile is by default left aligned, but you can change it using the setHorizontalAlignment() method.

Steps to Set Horizontal Alignment of Content in a JTextField

Following are the steps to set the Horizontal Alignment of content in a JTextField ?

  • Import the required Java Swing packages.
  • Create a JFrame and set layout manager.
  • Create JLabel and JTextField then set horizontal alignment.
  • Align the text in the JTextField to the right.
  • Put the label and text field in the frame.
  • Set the frame size and display it.

Java Program to Set Horizontal Alignment of Content in a JTextField

Below is the Java program to set the 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

Code Explanation

The code begins by importing the necessary packages for creating a GUI application with Java Swing. A JFrame named "Demo" is created as the main window, and its layout is set to FlowLayout for easy arrangement of components. A JLabel is added to label the JTextField where users will enter their email ID. The JTextField is initialized with a width of 20 columns, and its text alignment is set to the right using the setHorizontalAlignment() method. Both the label and text field are added to the frame. Finally, the frame's size is set to 550x250 pixels, and it is made visible to display the GUI.

Updated on: 2024-08-29T15:54:48+05:30

3K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements