I created a dialog with a jpanel inside it, and that jpanel will be still referenced if I get rid of the dialog. I want to destroy that dialog and everything in it when I click
You can override the finalize() method (see http://java.sun.com/j2se/1.4.2/docs/api/java/lang/Object.html#finalize%28%29) to perform cleanup when an object is destroyed.
However, unlike C++ there is no guarantee when will this method get called. In C++ you have stack-stored objects which are destroyed when execution leaves the scope in which they were defined.
In Java all object are stored on the heap. They will be finalized when the Garbage collector decides to collect them (implies that they are not reachable from your app) but you don't know when will the GC kick in. Thus, if you have some cleanup that must take place at a certain point (e.g., closing a file so that it can be written to) you have to code it yourself and not rely on the finalize() method being called.
The typical pattern for doing that is based on a try ... finally
block:
X x = null;
try {
// ... do some stuff
x = ... // obtain an object
... // do some stuff
}
finally {
if(x != null)
x.close(); // Perform cleanup WRT x
}
(Admittedly, ugly)