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?
No, as far as you access only non-graphical objects such as string from your example.