对于主窗口,可以使用下面的方法关闭,整个程序也相应退出,
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
但是,如果要关掉子窗口,子窗口的相关资源也要释放,但是主程序不能退出,那么就要使用dispose()方法
import javax.swing.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;
public class Test extends JFrame {
public static void main(String[]args){
Test t = new Test();
t.launch();
}
public void launch(){
try{
UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
} catch(Exception e){
e.printStackTrace();
}
JMenuBar menuBar = new JMenuBar();
JMenu menu = new JMenu("menu");
JMenuItem item = new JMenuItem("item");
menu.add(item);
item.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
final JFrame child = new JFrame("popupFrame");
child.setDefaultCloseOperation(DO_NOTHING_ON_CLOSE);
child.addWindowListener(new WindowAdapter() {
@Override
public void windowClosing(WindowEvent e) {
//调用这个方法之后,child 的相关资源全都会释放。
child.dispose();
}
});
child.setSize(260,150);
child.setLocation(400,300);
child.setVisible(true);
}
});
menuBar.add(menu);
setJMenuBar(menuBar);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setLocation(300,200);
setSize(300,200);
setVisible(true);
}
}