有没有办法使用两个不同的应用程序添加和删除系统托盘图标?

时间:2015-01-14 10:25:41

标签: java windows-services swt system-tray

我能够在单个应用程序中执行此操作,但我需要使用两个不同的应用程序执行此操作:

  • 添加SystemTray图标
  • 第二步删除SystemTray图标

这是我到目前为止所尝试的,它在单一应用中表现良好:

public static void main(String[] args) throws Exception {
    // Check the SystemTray support
    if (!SystemTray.isSupported()) {
        logger.info("SystemTray is not supported");
        return;
    }

    final PopupMenu popup = new PopupMenu();
    ClassLoader classLoader = Thread.currentThread().getContextClassLoader();
    InputStream inputStream = classLoader.getResourceAsStream("img.png");
    Image img = ImageIO.read(inputStream);

    final TrayIcon trayIcon = new TrayIcon(img, TOOL_TIP);
    processTrayIcon = trayIcon;
    final SystemTray tray = SystemTray.getSystemTray();

    // Create a popup menu components
    MenuItem startItem = new MenuItem("Start");

    MenuItem stopItem = new MenuItem("Stop");

    MenuItem exitItem = new MenuItem("Exit");

    // Add components to popup menu
    popup.add(startItem);
    popup.add(stopItem);
    popup.add(exitItem);

    trayIcon.setPopupMenu(popup);

    trayIcon.setImageAutoSize(true);

    try {
        tray.add(trayIcon);
    } catch (AWTException e) {
        logger.error("TrayIcon could not be added.", e);
        return;
    }

    // Add listener to exitItem.
    exitItem.addActionListener(new ActionListener() {
        public void actionPerformed(ActionEvent e) {
            stopProcess();
            tray.remove(trayIcon);
            System.exit(0);
        }
    });

    // Add listener to startItem.
    startItem.addActionListener(new ActionListener() {
        public void actionPerformed(ActionEvent e) {
            startProcess();
        }
    });

    // Add listener to stopItem.
    stopItem.addActionListener(new ActionListener() {
        public void actionPerformed(ActionEvent e) {
            stopProcess();
        }
    });
}

/**
 * This method will start a thread that will 
 * show a popup message from the system tray when the application started successfully.
 */

private static void startProcess() {

    Thread thread = new Thread(new Runnable() {

        @Override
        public void run() {
        // Starts a service

        }
    });

    thread.start();
}

/**
 * This method will start a thread that will 
 * show a popup message from the system tray when the application stopped successfully.
 */

private static void stopProcess() {

    Thread thread = new Thread(new Runnable() {

        @Override
        public void run() {
            //Stops a service           
        }
    });

    thread.start();
}

感谢任何帮助..

0 个答案:

没有答案