2

I work on a Java application consisting (as yet) of a regular Window (JFrame) and a JDialog called by a menuitem in the first:

public class MainWindow {
    private JFrame frame;
    public MyDialog dialog;
    /* ... */
    private void initialize() {
         mnNew = new JMenuItem("New...");
         mnNew.addActionListener(new ActionListener() {
             public void actionPerformed(ActionEvent arg0) {
             dialog = new MyDialog();
             }
         });
     }
}

And MyDialog is defined as follows:

public class MyDialog extends JDialog {

    public MyDialog() {
        /* ... */
        JButton cancelButton = new JButton("Cancel");
        cancelButton.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent arg0) {
                MyDialog.this.dispatchEvent(new WindowEvent(MyDialog.this,
                                            WindowEvent.WINDOW_CLOSING));
                MainWindow.window.matchMaker = null;
            }
        });
        /* ... */
        setDefaultCloseOperation(JDialog.DISPOSE_ON_CLOSE);
        setVisible(true);
    }
}

Everything works fine, but my Task Manager reports that each time I open and then close MyDialog, the program consumes more and more memory. Why?

mKorbel
  • 109,525
  • 20
  • 134
  • 319
Sventimir
  • 1,996
  • 3
  • 14
  • 25

2 Answers2

2

Instanciate MyDialog once:

public class MainWindow {
   private JFrame frame;
   private final MyDialog dialog = new MyDialog();

removes setVisible(true) in MyDialog constructor.

To show the dialog just do setVisible( true )

Aubin
  • 14,617
  • 9
  • 61
  • 84
2
Community
  • 1
  • 1
mKorbel
  • 109,525
  • 20
  • 134
  • 319
  • 1
    Thanks a lot. But shouldn't `MyDialog` be removed from memory after disposal and setting `dialog` variable to `null`? Anyway, it does nothing. Now I create MyDialog once in MainWindow constructor, setting its visibility to false. I make it visible with a function within MainWindow and invisible with another - in MyDialog, but memory is still leaking whenever I close and reopen the Dialog. – Sventimir Apr 07 '13 at 16:25
  • this is possible only by using static variables, – mKorbel Apr 07 '13 at 16:54