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 fram开发者_运维知识库e = 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();
}
});
}
}
textField.setComponentOrientation(ComponentOrientation.RIGHT_TO_LEFT);
I'm not sure I understand your question. Normally you create a JTextField with code like:
JTextField textField = new JTextField(10);
This gives the text field a fixed preferred size which is respected depending on the layout manager being used.
It sounds like you are doing something like:
JTextField textField = new JTextField();
In which case I don't think the text field has a size. Can you even add character to it? Well maybe the solution in this case is to add a ComponentListener to the text field and keep track of the original size. Every time the size changes you change the location of the text field by the difference in the size. Again this may or may not work depending on the layout manager.
If you need more help post your SSCCE showing the problem.
精彩评论