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 because main_f isn’t a variable. Can you help me?
Suggestion:
Make the
JFrameinstance a field of theMainWindowclass, and provide an accessor method for it.And then in the
Disposingclass, you should have aMainWindowinstance, where you’ll simply do the following to dispose of itsJFrameinstance:Recommendation:
Edit:
This is to address the errors that you’re seeing:
With regard to the first error, this is because in the example I provided, I used the
finalmodifier. This field must be initialized upon object creation. Therefore, you must have more than one constructor. To resolve this, either remove thefinalmodifier, or initialize themain_ffield in every constructor ofMainWindow.With regard to the second error,
mainWindowInstanceis something that I left for you to create. Here’s a “for instance” –