How do I right justified JTextField contents?

To right justified a JTextField contents we can call the setHorizontalAlignment(JTextField.RIGHT) method of the JTextField class.

package org.kodejava.example.swing;

import javax.swing.*;
import java.awt.*;

public class TextFieldRightJustify extends JFrame {
    public TextFieldRightJustify() {

    private void initComponents() {
        setSize(200, 200);

        Container container = getContentPane();
        container.setLayout(new FlowLayout(FlowLayout.LEFT));

        JTextField textField = new JTextField(15);
        textField.setPreferredSize(new Dimension(100, 20));
        // Right justify the JTextField contents


    public static void main(String[] args) {
        SwingUtilities.invokeLater(new Runnable() {
            public void run() {
                new TextFieldRightJustify().setVisible(true);


Programmer, runner, recreational diver, live in the island of Bali, Indonesia. Mostly programming in Java, Spring Framework, Hibernate / JPA. Support me by donating.

Leave a Reply