1

嗨,我正在尝试动态更改我在 java 中拥有的托盘图标。例如,他们的图标是灰色的正方形。当用户单击托盘菜单中的项目时,我希望灰色方块将图像切换为红色方块。

这是我当前的托盘图标代码。

public class Utils {

    private static Image iconImage;
    private static Image iconImage2;
    private static SystemTray sysTray;
    private static PopupMenu menu;
    private static MenuItem item1;
    private static MenuItem item2;
    private static MenuItem item0;
    private static TrayIcon trayIcon;
    private static TrayIcon trayIcon2;

    public static void loadTrayIcon() {
        JFrame frame = new JFrame("AC Tray Frame");

        frame.setLayout(new GridLayout(1, 3)); 

        if (SystemTray.isSupported()) {
            sysTray = SystemTray.getSystemTray();

            iconImage  = Toolkit.getDefaultToolkit().getImage("osx_tray_icon.png");
            iconImage2  = Toolkit.getDefaultToolkit().getImage("loading.gif");

            menu = new PopupMenu();

            item0 = new MenuItem("This is a test");
            item0.setEnabled(false);
            item1 = new MenuItem("Test");
            item2 = new MenuItem("Exit");

            menu.add(item0);
            menu.addSeparator();
            menu.add(item1);
            menu.addSeparator();
            menu.add(item2);

            item1.addActionListener(new ActionListener() {
                public void actionPerformed(ActionEvent e) {
                    try {
                        system.out.println("hi");
                    } catch (IOException e1) {
                        e1.printStackTrace();
                    }
                }
            });

            item2.addActionListener(new ActionListener() {
                public void actionPerformed(ActionEvent e) {
                    System.exit(0);
                }
            });

            trayIcon = new TrayIcon(iconImage, "Test Title", menu);

            try {
                sysTray.add(trayIcon);
            }
            catch(AWTException e) {
                System.out.println(e.getMessage());
            }
        }
    }
4

1 回答 1

2

您只是想使用TrayIcon#setImagewhich 将更改显示的图标TrayIcon

于 2014-06-09T21:18:20.817 回答