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);
}
}