Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

JTextField : How to set text on the left of JTextField when text too long

I have a long String that I want to display in a JTextField. If the String is too long, it is showing the right-portion of the String, rather than the left portion, even when I use setHorizontalAlignment(JTextField.LEFT)

For example, if my String is "JTextField example , this text is too long", it should show as...

|----------------------|
| JTextField example ..|
|----------------------|

but instead it shows as...

|----------------------|
| this text is too long|
|----------------------|

Could someone please suggest how this can be fixed.

like image 902
manhnt Avatar asked Apr 25 '12 04:04

manhnt


People also ask

How do I limit the length of a JTextField?

We can restrict the number of characters that the user can enter into a JTextField can be achieved by using a PlainDocument class.

How do I center text in a JTextField?

Just use the setBounds attribute. Jtextfield. setBounds(x,x,x,x);

What is the difference between JTextField and JTextArea?

The main difference between JTextField and JTextArea in Java is that a JTextField allows entering a single line of text in a GUI application while the JTextArea allows entering multiple lines of text in a GUI application.

Can the program put text in JTextField?

The class JTextField is a component that allows editing of a single line of text.


1 Answers

the horizontalAlignement works fine when the size of the field is bigger than the number of chars of the string, but if it is smaller it only does the LEFT_ALIGNMENT with the setText of its creation, not with any later setText.

You could force the position of the caret to the begining of the text using:

myTextField.setCaretPosition(0);
like image 79
Zaz Gmy Avatar answered Oct 04 '22 22:10

Zaz Gmy