![](/img/trans.png)
[英]Exception in thread “AWT-EventQueue-0” java.awt.HeadlessException when running arduino on bash (via Windows subsystem of Linux)
[英]Ending the Java AWT thread when there are no more windows open
我有一個JFrames的ArrayList,我希望能夠檢測到所有窗口何時關閉,從而結束程序。
到目前為止,每次創建JFrame時,我都會將其添加到“數組列表”中。 我還實現了一個WindowListener,並在每次調用windowClosing()時從列表中刪除該JFrame。
但是,我的問題是,列表為空時程序不會結束。 通常,我使用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將自動退出
import java.awt.EventQueue;
import javax.swing.JFrame;
import javax.swing.UIManager;
import javax.swing.UnsupportedLookAndFeelException;
public class MainFrame extends JFrame {
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
@Override
public void run() {
try {
UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
} catch (ClassNotFoundException | InstantiationException | IllegalAccessException | UnsupportedLookAndFeelException ex) {
ex.printStackTrace();
}
newFrame();
newFrame();
newFrame();
}
});
}
public MainFrame() {
setDefaultCloseOperation(DISPOSE_ON_CLOSE);
setSize(800, 600);
setVisible(true);
}
public static void newFrame() {
new MainFrame();
}
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.