Search code examples
javaswingjtextfield

JTextField setDocument overwrites text


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?


Solution

  • 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.