I am making a small application, with a JMenuBar, now, I got a menuitem, which is a store, which opens a new JFrame. When I click the button, a new JFrame appears, all good. But, when I click the close button of my Store JFrame, I don’t want my main JFrame to close. If I press the store-close-button now, it will close down both the main JFrame, and the Store JFrame, any help on making like, 2 separate close buttons for these 2 JFrames? Code for main JFrame:
public static void main(String[] args){
//Create new JFrame
JFrame frame = new JFrame();
frame.setTitle("MrStan");
frame.setSize(200, 200);
frame.setDefaultCloseOperation( JFrame.EXIT_ON_CLOSE );
frame.setJMenuBar(menubar);
//Set location of JFrame
Dimension dim = Toolkit.getDefaultToolkit().getScreenSize();
int screenWidth = (int) dim.getWidth();
int screenHeight = (int) dim.getHeight();
frame.setLocation(screenWidth / 2 - 200, screenHeight / 2 - 200);
//Set ContentPane to JPanel
MrStan panel = new MrStan();
frame.setContentPane(panel);
//Make the user not be able to resize
frame.setResizable(false);
//Make the JFrame visible
frame.setVisible(true);
}
My store JFrame:
public MrStanStore(){
JFrame frame2 = new JFrame();
frame2.setTitle("Store");
frame2.setSize(300, 200);
frame2.setDefaultCloseOperation( JFrame.EXIT_ON_CLOSE );
//Set location of JFrame
Dimension dim = Toolkit.getDefaultToolkit().getScreenSize();
int screenWidth = (int) dim.getWidth();
int screenHeight = (int) dim.getHeight();
frame2.setLocation(screenWidth / 2 - 200, screenHeight / 2 - 200);
//Make the user not be able to resize
frame2.setResizable(false);
//Make the JFrame visible
frame2.setVisible(true);
}
Don’t use 2 JFrames. Generally applications should have a single JFrame and then you use JDialogs for support windows. JDialogs to not support exiting the VM when then are closed so this will not be an issue.
If you do use a JFrame then you should use DISPOSE_ON_CLOSE. Then when the last frame is closed the VM will exit automatically.