繁体   English   中英

java SystemTray.add(TrayIcon)在退出时挂起Swing GUI

[英]java SystemTray.add(TrayIcon) hangs Swing GUI on exit

这是一个有趣的错误(读:我可能错过了一些东西)在Java Swing我花了最近2天试图追踪。

首先,创建一个SSCCE 干得好。

class GUI extends JFrame{
    public static void main(String[] args){
        // All GUI work should be handled in the EDT.
        SwingUtilities.invokeLater(new Runnable(){
            @Override
            public void run() {
                new GUI().setVisible(true);
            }
        });
    }

    GUI(){
         // Make a nice icon
        ImageIcon img = new ImageIcon(this.getClass().getClassLoader().getResource("img/1.png"));

        // Make a TrayIcon with the image
        SystemTray sysTray = SystemTray.getSystemTray();
        TrayIcon trayIcon = new TrayIcon(img.getImage());
        try {
            sysTray.add(trayIcon);
        }
        catch(AWTException e) {
            e.printStackTrace();
           System.out.println("System Tray unsupported!");
        }

        this.setTitle("Example GUI");
        this.setIconImage(img.getImage());
        this.setDefaultCloseOperation(DISPOSE_ON_CLOSE);
    }
}

如果我运行它并关闭Window,我会期望它处理,并且各种Threads终止。 如果我注释掉“Make a TrayIcon”try / catch块就是这种情况。

sysTray.add()行似乎没有创建Exception,但是在代码中使用它会阻止Threads终止,因为代码在AWT-EventQueue Thread中的wait()上挂起。

这是一个错误,还是我遗漏的东西?

干杯全都。

要在关闭程序时使程序正确终止,需要将DefaultCloseOperation设置为EXIT_ON_CLOSE ,如下所示:

GUI.setDefaultCloseOperation(EXIT_ON_CLOSE);

EXIT_ON_CLOSEJFrame中定义,因此您无需定义它或从任何地方导入它。

检查API以获取更多退出操作:

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM