【发布时间】:2016-02-09 14:14:19
【问题描述】:
我有一个 JFrame 的 ArrayList,我希望能够检测到所有窗口何时关闭,从而结束程序。
到目前为止,我每次制作 JFrame 时,都会将其添加到数组列表中。我还实现了一个 WindowListener,并在调用 windowClosing() 时从列表中删除该 JFrame。
然而,我的问题是当 List 为空时程序不会结束。通常,我使用 frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE),但现在我有多个窗口,这不起作用。我应该手动调用 System.Exit(0);还是有更优选的终止程序的方法。
谢谢
样本
public class MainFrame extends JFrame{
private static final ArrayList<MainFrame> frameList = new ArrayList<MainFrame>();
public static void main(String[] args){
newFrame();
newFrame();
newFrame();
}
public MainFrame(){
addWindowListener(new Listener());
setSize(800, 600);
setVisible(true);
}
class Listener implements WindowListener{
public void windowClosing(WindowEvent arg0) {
frameList.remove(MainFrame.this);
if(frameList.size() == 0){
//End Program
}
}
}
public static void newFrame() {
frameList.add(new MainFrame());
}
}
【问题讨论】:
-
将
defaultCloseOperation属性设置为DISPOSE_ON_CLOSE将允许JVM 执行此操作...
标签: java multithreading swing jframe awt