1

I have a JFrame and I have created an object to open it and close it all around my project. This means I am using only one object for that JFrame.

When I call dispose() method to close that frame I expect it to be reset to a new JFrame on next setVisible(true) call. But i can still see the fields filled with value from the previous setVisible(true) call even after i called dispose() on closing it.

How do I flush the stored values from that frame so that I get a new form when i call setVisible(true)?

Brad Mace
  • 27,194
  • 17
  • 102
  • 148
Deepak
  • 6,684
  • 18
  • 69
  • 121

2 Answers2

1

dispose() doesn't reset your components but you can create new JFrame manually:

previous.setVisible(false);
previous = new JFrame();
previous.setVisible(true);
lukastymo
  • 26,145
  • 14
  • 53
  • 66
  • but i might need to open the frame like this 1000 times a day.. if i keep on creating new frames like this will it affect the performance ? – Deepak Mar 23 '11 at 00:33
  • 1
    Performance - I don't think so but you can test it. Memory - if you haven't any references to old frames then GC will removes it correctly. My second proposition is to manually clearing your components: e.g: setText(""); etc. – lukastymo Mar 23 '11 at 00:42
  • While technically true, it can still degrade performance, since there's no guarantee when the GC will run. http://stackoverflow.com/questions/6309407/remove-top-level-container-on-runtime – Spencer Kormos Nov 10 '11 at 18:00
1

Try adding a WindowListener:

frame.addWindowListener(new WindowAdapter() {
    public void windowClosed(WindowEvent e) {
         MyJFrame frame = (MyJFrame) e.getSource();
         frame.someTextField.setText("");
         ...
    }
});

This isn't tested but should be close enough to get you started.

Brad Mace
  • 27,194
  • 17
  • 102
  • 148
  • thank you.. Actually i am looking for any methods similar to dispose() but if there is no other way then i have to try these methods. Currently i am using the method you just told me.. – Deepak Mar 23 '11 at 01:21
  • 1
    There isn't any built-in method that will automatically do it, but you can override `dispose` or `setVisible` and clear your fields there after calling the parent class's implementation if you'd rather do it that way. – Brad Mace Mar 23 '11 at 01:54