2

I have tried searching around for this question, as I imagine it must have been asked at some point, but this was the closest thing I could find Remove Top-Level Container on Runtime.

My question is, is it safe execute code in a JDialog, after having called dispose() on that dialog, if the dispose is done in a try and the executing code is done in a finally?

Here is an example to demonstrate what I am asking:

import java.awt.EventQueue;
import javax.swing.JDialog;

public class DisposeTestDialog extends JDialog {
    private final String somethingToPrint;

    public DisposeTestDialog(String somethingToPrint) {
        this.somethingToPrint = somethingToPrint;
    }

    public void showAndDispose() {
        setVisible(true);
        // Do something
        setVisible(false);
        try {
            dispose();
        }
        finally {
            System.out.println(somethingToPrint);
        }
    }

    public static void main(String[] args) {
        EventQueue.invokeLater(new Runnable() {
            @Override
            public void run() {
                DisposeTestDialog dialog = new DisposeTestDialog("Can this be safely printed?");
                dialog.showAndDispose();
            }

        });
    }
}

From what I know of the dispose() process, and finally blocks, I would say it should work fine, if not a great idea. Indeed running the above code does successfully print.

Is it possible though that a GC could start in between the try/finally and cause some issue?

Community
  • 1
  • 1
Ryan Latham
  • 59
  • 1
  • 8
  • If you need for your class to be persistent, don't extend a JDialog. Use a JDialog. Only extend a Swing Component when you want to override one of the component methods. – Gilbert Le Blanc Mar 27 '14 at 14:50
  • @GilbertLeBlanc Yeah that was really only for this example. My actual use case is vastly different. – Ryan Latham Mar 27 '14 at 14:58

1 Answers1

1

No, as far as you access only non-graphical objects such as string from your example.

Kojotak
  • 2,020
  • 2
  • 16
  • 29
  • So you're saying as long as I don't do something that would access part of the Dialog's framework, then I should be fine? – Ryan Latham Mar 27 '14 at 15:00