0

Problem solved, see How to prevent the TrayIcon popup to occupy the whole dispatcher thread

When I right click the system tray icon, it seems blocks the GUI. The thread is still running but the JFrame background color will stop updating. How to solve it? I tried put initSystemTray in another Thread but not working. Here is the code:

import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;

public class Tester1 {
    static JFrame jFrame = new JFrame();
    static boolean isBlack = true;

    public static void main(String[] args) throws AWTException {
        initSystemTray();
        initJFrame();
    }

    private static void initJFrame() {
        jFrame.setSize(200, 200);
        jFrame.setVisible(true);
        new Thread(() -> {
            int delay = 1000;
            Timer timer = new Timer(delay, new AbstractAction() {
                @Override
                public void actionPerformed(ActionEvent ae) {
                    if (isBlack) {
                        System.out.println("Set to Black");
                        jFrame.getContentPane().setBackground(Color.black);
                        isBlack = false;
                    } else {
                        System.out.println("Set to White");
                        jFrame.getContentPane().setBackground(Color.white);
                        isBlack = true;
                    }
                }
            });
            timer.setRepeats(true);
            timer.start();
        }).start();
    }

    private static void initSystemTray() throws AWTException {
        SystemTray tray = SystemTray.getSystemTray();
        PopupMenu popupMenu = new PopupMenu();
        MenuItem menuItem = new MenuItem("A Menu");
        popupMenu.add(menuItem);
        TrayIcon trayIcon = new TrayIcon(Toolkit.getDefaultToolkit().getImage("imgs\\icon.png"), "Test", popupMenu);
        tray.add(trayIcon);
    }
}
Yuhao Tang
  • 11
  • 2
  • That code stomps all over Swing threading rules. If you need to do Swing animation, don't call `Thread.sleep` but rather use a Swing Timer. – Hovercraft Full Of Eels Jul 09 '20 at 02:00
  • I updated my code, now it uses `Timer` instead of `Thread.sleep`. But problem still exists. Also I might know what happens, the right click event of system tray is on event dispatch thread. So it will block other any other changing UI actions. But I don't know how to work around it and let the system tray independent with the main window. The related question does not fully resolove my problem, should I ask a new one? @HovercraftFullOfEels – Yuhao Tang Jul 09 '20 at 06:55

0 Answers0