2

I'm trying to make JTextField display dots when its content is longer then display area. I would like to have the same behaviour like in JTable, where when I resize column the text inside changes - when its to long only begining of it is displayed and then there are three dots (to see what I have in mind please run first example from this link and change column size - I'm not allowed to post images because I'm new here;) )

Is is possible? Only solution that I have in mind is extending JTextField with a class that will have additional field oryginalText and will behave like that (didn't test it, it's just a proposal, dimension of the JtextField will not change):

import javax.swing.JTextField;

public class MyTextField extends JTextField {

    private String oryginalText;
    private int length;

    @Override
    public void setText(String text) {
        oryginalText = text;
        if (oryginalText.length() > length)
            super.setText(oryginalText.substring(0, length - 2) + "..");
        else
            super.setText(oryginalText);
    }
}

any ideas?

Alex K
  • 22,315
  • 19
  • 108
  • 236
marekk
  • 237
  • 2
  • 11
  • 5
    Doesn't sound very user friendly actually. That is really a non-standard behaviour of a text field. – aioobe Feb 13 '12 at 16:21
  • 2
    Agree, but see also [*Ideal method to truncate a string with ellipsis*](http://stackoverflow.com/q/3597550/230513). – trashgod Feb 13 '12 at 16:59
  • 3
    The behavior you see is the behavior of a `JLabel`. If your text is non-editable, consider using that instead of a `JTextField` – Robin Feb 13 '12 at 17:00
  • @Robin thanks for clarifying, unfortunately this field must be editable, but at least now I know what component is responsible for showing text in such a way – marekk Feb 14 '12 at 08:52
  • 1
    @aioobe true, its not typical behaviour of this component but due to layout restrictions I have fields that can take more characters then they show, so I must have some way to show it after user leaves the field - I think I will go with the idea of MyTextField or something similiar – marekk Feb 14 '12 at 08:58
  • possible duplicate of [How to make an overflowed TextArea truncate text and show ellipsis in the end?](http://stackoverflow.com/questions/6747156/how-to-make-an-overflowed-textarea-truncate-text-and-show-ellipsis-in-the-end) – Morgen Apr 24 '15 at 23:34

1 Answers1

0

Over your idea of extending JTextField and storing the original (non trimmed) value:

Show the textfield as disabled (or not editable) and with trimmed text. When the user clics the textfield make it enabled/editable and show the whole original text.

Then again when the user press enter or the focus exits of the textfield: disable/not editable and trimmed text.

Paco Abato
  • 3,920
  • 4
  • 31
  • 54