javaswingjdialoggui-builder

jtextfield retains value in jdialog after closing jdialog


I'm new to Java and Swing. I created a jframe and I added a menubar and MenuItem in it.

On clicking a menu item, a jdialog should open. Now the jdialog has a jtextfield in it and a jlabel. Now the problem for me is 'when dialog is opened for first time, the textfield is empty and thats correct. Now i close the jdialog and i open it again but now instead of getting an empty textfield in jdialog, i get the data entered previously' which is not what should happen as the jdialogs 'default close operation' property is set to 'dispose'. but that is not happening for me...

I dont know what i'm doing wrong. I have never tried applet/swing before in any other way (consider this as my first demo learning programme)

Image Second Image here

Second Image here


Solution

  • The JTextField is retaining it's value because it isn't being affected by the JDialog closing, instead it is being hidden as it's parent (the JDialog) is invisible

    Setting the dialog to dispose isn't re-initialising the child components, so they keep their values. Some additional information on this behaviour is available here:


    One way you can prevent / control this is by "informing" the dialog to wipe the textfield as it is closing by adding a WindowEvent and providing the necessary functionality in the windowClosing() method

    Netbeans gui-builder will generate this for you with the following:

    Providing:

    private void jDialog1WindowClosing(java.awt.event.WindowEvent evt) {                                       
        // TODO add your handling code here:
    } 
    

    In which you can add: textfield.setText(""); to clear the textfield


    Another approach is to create your own dialog and setting up the components in the constructor. As creating a new instance will contain the components with their default values, effectively resetting it