7

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.

wattostudios
  • 8,666
  • 13
  • 43
  • 57
manhnt
  • 643
  • 1
  • 11
  • 24
  • 9
    You can use `setCaretPosition(0)` to set the position to the left side of the `JTextField` but in order to be able to scroll you are going to have to add the `JTextField` to a `JScrollPane` – twain249 Apr 25 '12 at 04:14
  • 1
    @twain249 : Why not put that, as an answer ? Too good, will work as expected :-) – nIcE cOw Apr 25 '12 at 04:21
  • 1
    @twain249: Even without a `JScrollPane`, `JTextField` can scroll using the left and right arrow keys; `setScrollOffset()` looks promising, too. – trashgod Apr 25 '12 at 04:40

1 Answers1

12

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);
Zaz Gmy
  • 4,236
  • 3
  • 19
  • 30