Disposing JFrame from another class
Suggestion:
Make the JFrame
instance a field of the MainWindow
class, and provide an accessor method for it.
public final class MainWindow{
private final JFrame main_f;
public MainWindow(){
main_f = new JFrame("xx");
main_f.getContentPane().setLayout(new BorderLayout());
main_f.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
.
.
.
}
public final JFrame getMainFrame(){
return main_f;
}
.
.
.
}
And then in the Disposing
class, you should have a MainWindow
instance, where you'll simply do the following to dispose of its JFrame
instance:
mainWindowInstance.getMainFrame().dispose();
Recommendation:
- Read the Learning the Java Language tutorial. This is basic OOP.
Edit:
This is to address the errors that you're seeing:
- variable main_f might not have been initialized
- cannot find symbol "mainWindowInstance"
With regard to the first error, this is because in the example I provided, I used the final
modifier. This field must be initialized upon object creation. Therefore, you must have more than one constructor. To resolve this, either remove the final
modifier, or initialize the main_f
field in every constructor of MainWindow
.
With regard to the second error, mainWindowInstance
is something that I left for you to create. Here's a "for instance" -
public class Disposing{
private MainWindow mainWindowInstance;
public Disposing(){
mainWindowInstance = new MainWindow();
.
.
.
}
public void diposeMainFrame(){
mainWindowInstance.getMainFrame().dispose();
}
}
Related videos on Youtube
Makaroni
Updated on June 27, 2022Comments
-
Makaroni almost 2 years
How can I dispose
JFrame
from another class? My code is listed below.public class MainWindow { JFrame main_f = new JFrame("xx"); main_f.getContentPane().setLayout(new BorderLayout()); main_f.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE); . . . }
Disposing class:
public static void DisposingJFrame (){ . . . MainWindow.main_f.dispose(); }
MainWindow.main_f.dispose()
won't work becausemain_f
isn't a variable. Can you help me? -
mre almost 13 years@Makaroni, Also, if you made
main_f
astatic
field, this would work the way you're trying to dispose of it, but that's not really OOP. -
Makaroni almost 13 yearsIDE gives me 2 errors now: 1st. "variable main_f might not have been initialized", and 2nd: cannot find symbol "mainWindowInstance". Should I import something?
-
mre almost 13 years@Makaroni, What errors? Can you include your updated code? Please provide this information as an edit to your question.