How to ceate right justified JTextField in Java?

Java 8Object Oriented ProgrammingProgramming

To create right justified JTextField, set the alignment to be RIGHT. Here, we will be using the setHorizontalAlignment() method as well and within that the alignment would be set.

Create a JTextField −

JTextField emailId = new JTextField(20);

Now, align it to the right −

emailId.setHorizontalAlignment(JTextField.RIGHT);

The following is an example to create right justified JTextField −

Example

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("Enter emailid...");
      JLabel label;
      frame.setLayout(new FlowLayout());
      label = new JLabel("TextField (Right Justified)", SwingConstants.LEFT);
      JTextField emailId = new JTextField(20);
      emailId.setHorizontalAlignment(JTextField.RIGHT);
      frame.add(label);
      frame.add(emailId);
      frame.setSize(550,250);
      frame.setVisible(true);
   }
}

This will produce the following output. Now, if yiu will tyoe any text in the component, it would begin from the right −

Output

raja
Published on 04-Jun-2019 09:29:45
Advertisements