I have a main JFrame window with a JButton. When I click on the button a new window is opened, but when I want to close the second window, both window are closed! I want the first to opened all the time. Is there a way to only close the second window? Preciate some help! Thanks!
EDIT: I add new code to show my problem. Class GUI1 has a main frame and a button to open a second frame, GUI2, that has has a button to close GUI2 frame. It’s the closing part of GUI2 I can’t solve. The code is simple and just for testing.
GUI1
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
public class GUI1 extends JFrame implements ActionListener{
JButton btn1;
Container contentPane;
public GUI1()
{
setTitle("GUI 1");
setResizable(false);
setSize(600,300);
setDefaultCloseOperation(EXIT_ON_CLOSE);
contentPane = getContentPane();
contentPane.setLayout(new FlowLayout());
btn1 = new JButton("Open GUI 2 frame");
contentPane.add(btn1);
btn1.setFocusable(false);
btn1.addActionListener(this);
}
public void actionPerformed(ActionEvent event){
if(event.getSource() == btn1)
{
GUI2 frame2 = new GUI2();
frame2.setVisible(true);
}
}
public static void main(String[] args) {
GUI1 frame = new GUI1();
frame.setVisible(true);
}
}
GUI2
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
public class GUI2 extends JFrame implements ActionListener {
Container contentPane;
JButton btn2;
public GUI2()
{
setTitle("GUI 2");
setResizable(false);
setSize(400,200);
setDefaultCloseOperation(DISPOSE_ON_CLOSE);
contentPane = getContentPane();
contentPane.setLayout(new FlowLayout());
btn2 = new JButton("Close GUI 2 frame");
contentPane.add(btn2);
btn2.addActionListener(this);
}
public void actionPerformed(ActionEvent event){
if(event.getSource() == btn2)
{
// Close GUI2 ??
}
}
}
After a second read, I agree with others when they say you shouldn’t be creating and discarding JFrames (or using multiple JFrames at all). But if you really want to go that route, I’d suggest:
JFrame.HIDE_ON_CLOSEinstead of3(exit on close) – don’t use magic numbers;Update: the steps to apply the above suggestions to your architecture are:
GUI1class –private GUI2 frame– and only create it once (in the constructor of GUI1 for instance);actionPerformed, only useframe.setVisible(true)– since the frame was already created;DISPOSE_ON_CLOSEon GUI2, if you wanted, butHIDE_ON_CLOSEis more appropriate;GUI2– the JFrame – who is implementing the action listener, you already have a reference to it:this! Usethis.setVisible(false)or simplysetVisible(false).