Search code examples
javaswingjtextfielddirection

Change the direction of growth for a JTexField object


I need to change the direction of the growth of JTextField object when more characters are added to it. Currently when I add more stuff to it, it grows from left to right but I need this growth of the bounds of the JTextField from right to left. For e.g. when I add "StackOverflow" to this JTextField the o/p is,

<empty space>StackOverflow

but I want,

StackOverflow<empty space>

Can you guys help me with this? I tried setHorizontalAlignment. But it doesnt work. Thanks for any help.

EDIT : Added SSCCE for better explanation.

import java.awt.Container; import javax.swing.BoxLayout; import javax.swing.JButton; import javax.swing.JFrame; import javax.swing.JTextField;

public class JTextFieldExample { public static void addComponentsToPane(Container pane) { pane.setLayout(new BoxLayout(pane, BoxLayout.Y_AXIS));

    JTextField transitionEditorJTextField = new JTextField("StackOverFlow");
    pane.add(transitionEditorJTextField);

    System.out.println("If I add text to JTextFiled notice that it grows towards Right - which is normal. " 
                        + "But I want it to grow towards left.");
    JButton button = new JButton("Button.I.Am");
    pane.add(button);



}

/**
 * Create the GUI and show it.  For thread safety,
 * this method should be invoked from the
 * event-dispatching thread.
 */
private static void createAndShowGUI() {
    //Create and set up the window.
    JFrame frame = new JFrame("BoxLayoutDemo");
    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

    //Set up the content pane.
    addComponentsToPane(frame.getContentPane());

    //Display the window.
    frame.pack();
    frame.setVisible(true);
}

public static void main(String[] args) {
    //Schedule a job for the event-dispatching thread:
    //creating and showing this application's GUI.
    javax.swing.SwingUtilities.invokeLater(new Runnable() {
        public void run() {
            createAndShowGUI();
        }
    });
}

}


Solution

  • textField.setComponentOrientation(ComponentOrientation.RIGHT_TO_LEFT);