0

I created a JTextField (either with setting the text after the creation or in the constructor). After that I added a Document (setDocument) to the textfield and wondered why the text value of JTextField was empty.

Example:

JTextField field = new JTextField();
field.setText(textValue); // or instead setting the text in the constructor
field.setDocument(new TestDocument());
// text is no empty

Setting the document before the text fixes this entirely. I just wondered why this happens. Is it because the previously set text wasn't handled according to document?

Liso
  • 195
  • 5
  • 15
  • 3
    The text, you've set, is in `JTextField` is internally stored in the `Document`, so when you replace the document - the previouse text is lost. – Sergiy Medvynskyy Oct 23 '19 at 06:39

1 Answers1

1

Swing components work on a modified Model-View-Controller design.

  1. The Model (in this case the Document) contains the data. Note for other Swing components the Model is actually called an Model. For example you have a TableModel for a JTable or a ListModel for a JList.
  2. The View-Controller is the JTextField component. The job of the View is to paint the data in the Model.

When you add text to the text field you are really updating the Model. The Model then notifies the View that the data has changed and the text field is repainted.

So, if you add text to the Document via the setText(...) method and then set a new Document to the text field, as far as the View is concerned there is no text to paint.

Why are you using a custom Document? There are generally better options if you need to customize the behaviour of the text field.

camickr
  • 321,443
  • 19
  • 166
  • 288
  • The document was used to replace commas by dots. Can you give an example of a better option? – Liso Oct 24 '19 at 07:05
  • 1
    @Liso, You can use a `DocumentFilter` for this type of functionality. A `DocumentFilter` can be added to any Document. See: https://stackoverflow.com/questions/56870765/typed-charcter-of-my-keyboard-without-display-it-automoticlly-on-my-jtextpane/56871908#56871908 for an example that converts characters to upper case as they are typed. Your logic will be simpler. Your convertString(...) implementation would simply use the String.replaceAll(...) method to replace the commas with dots. – camickr Oct 24 '19 at 14:37