Search code examples
javaalignmentjtextfield

Adjust JTextField default alignment


I created 10 JTextFields, and now I want to align them to the right. I know this can be done with [nameTextField].setHorizontalAlignment(JTextField.RIGHT);, but I wonder if this can be done with one line of code. Since JTextField.setHorizontalAlignment(JTextField.RIGHT);, does not work, my question is: is this possible?


Solution

  • Since JTextField.setHorizontalAlignment(JTextField.RIGHT); does not work

    Let's understand why that doesn't work first. If we look at the documentation for JTextField we can see all the methods it contains under the Method Summary heading. It has a method setHorizontalAlignment(int alignment), which returns void. Note that the method is not declared as static (look in the leftmost column where it says void). Since the method is not static, we cannot call it on the class itself, but only on instances of the class.

    Is this possible?

    I think you have two options here:

    1. You can subclass JTextField, name it something such as RightAlignedTextField, and have it set the alignment by default. You can then use this instead of the plain ol' JTextField. OR
    2. You can write a method to adjust the alignment of all the text fields you plan to use.

    To use both in an example:

    import javax.swing.*;
    import java.awt.*;
    class RightAlignedTextField extends JTextField {
        public RightAlignedTextField(int columns) {
            super(columns);
            this.setHorizontalAlignment(RIGHT);
        }
    }
    public class Q21970358 extends JFrame {
        private final static long serialVersionUID = 0L;
        private JTextField t1 = new JTextField(30);
        private JTextField t2 = new JTextField(30);
        private JTextField t3 = new JTextField(30);
        private JTextField t4 = new JTextField(30);
        private JTextField t5 = new JTextField(30);
        private JTextField t6 = new RightAlignedTextField(30);
        public Q21970358() {
            super("Stack Overflow Q21970358");
            this.addTextFields();
            this.setVisible(true);
            this.setDefaultCloseOperation(EXIT_ON_CLOSE);
            this.setMinimumSize(new Dimension(400, 300));
        }
        public void alignAllRight(JTextField... fields) {
            for (JTextField t : fields) {
                t.setHorizontalAlignment(JTextField.RIGHT);
            }
        }
        public void addTextFields() {
            // Set all to align right
            // This is the part you're looking for
            // (2)
            this.alignAllRight(t1, t2, t3, t4, t5);
            JPanel panel = new JPanel();
            panel.add(t1);
            panel.add(t2);
            panel.add(t3);
            panel.add(t4);
            panel.add(t5);
            panel.add(t6); // (1)
            this.add(panel);
        }
        public static void main(String[] args) { new Q21970358(); }
    }