Creating tray icon using JavaFX

后端 未结 5 583
南方客
南方客 2021-02-07 15:48

I want to write a tray icon via JavaFx, but I only find that can write by awt. Is there any way that can write it use JavaFx?

It w

5条回答
  •  醉酒成梦
    2021-02-07 16:38

    To make a system tray try following code:

    Original document link: https://docs.oracle.com/javase/tutorial/uiswing/misc/systemtray.html

        //Check the SystemTray is supported
        if (!SystemTray.isSupported()) {
            System.out.println("SystemTray is not supported");
            return;
        }
        final PopupMenu popup = new PopupMenu();
    
        URL url = System.class.getResource("/images/new.png");
        Image image = Toolkit.getDefaultToolkit().getImage(url);
    
        final TrayIcon trayIcon = new TrayIcon(image);
    
        final SystemTray tray = SystemTray.getSystemTray();
    
        // Create a pop-up menu components
        MenuItem aboutItem = new MenuItem("About");
        CheckboxMenuItem cb1 = new CheckboxMenuItem("Set auto size");
        CheckboxMenuItem cb2 = new CheckboxMenuItem("Set tooltip");
        Menu displayMenu = new Menu("Display");
        MenuItem errorItem = new MenuItem("Error");
        MenuItem warningItem = new MenuItem("Warning");
        MenuItem infoItem = new MenuItem("Info");
        MenuItem noneItem = new MenuItem("None");
        MenuItem exitItem = new MenuItem("Exit");
    
        //Add components to pop-up menu
        popup.add(aboutItem);
        popup.addSeparator();
        popup.add(cb1);
        popup.add(cb2);
        popup.addSeparator();
        popup.add(displayMenu);
        displayMenu.add(errorItem);
        displayMenu.add(warningItem);
        displayMenu.add(infoItem);
        displayMenu.add(noneItem);
        popup.add(exitItem);
    
        trayIcon.setPopupMenu(popup);
    
        try {
            tray.add(trayIcon);
        } catch (AWTException e) {
            System.out.println("TrayIcon could not be added.");
        }
    

    Example system tray image in Windows 10

    To invoke method of Javafx from awt event handler you may follw the following way:

    yourAwtObject.addActionListener(e -> {
        Platform.runLater(() -> primaryStage.show());
    });
    

提交回复
热议问题