-2

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

Alex K
  • 22,315
  • 19
  • 108
  • 236
pratik
  • 3
  • 3
  • 1
    Consider using a `JOptionPane.showInputDialog(..)` instead. As for the dialog, either create a new one or (preferable) keep a reference to the text field and set it blank before opening. But for better help sooner, post a [MCVE] or [Short, Self Contained, Correct Example](http://www.sscce.org/) (as opposed to screenshots that tell us almost nothing worth knowing). – Andrew Thompson Jun 19 '16 at 13:07
  • here is my exact problem: https://www.youtube.com/watch?v=6mfFOG5szvw – pratik Jun 20 '16 at 06:11
  • Your exact problem is that you cannot distinguish between Java code and a youtube video. We are unable to help with that. – Andrew Thompson Jun 20 '16 at 06:13

1 Answers1

0

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:

  • Right click Dialog
    • Events
      • Window
        • WindowClosing

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

Community
  • 1
  • 1
Peter
  • 1,592
  • 13
  • 20