如何最小化靠近系统托盘的javafx平台?

Dar*_*nja 5 javafx javafx-8

我有一个具有2个阶段的应用程序,我不希望用户关闭第二个阶段,只需对其进行图标化即可。

目前,我正在使用oncloseRequest处理程序以最小化窗口-

secondaryStage.setOnCloseRequest(event -> {
    secondaryStage.setIconified(true);
    event.consume();
});
Run Code Online (Sandbox Code Playgroud)

我想在用户关闭窗口时在系统任务栏中显示一个图标。并且用户应该能够从托盘中重新打开窗口。

另外,如何确保第一阶段关闭时第二阶段也关闭?

Aup*_*upr 7

在 start 方法中设置以下属性

Platform.setImplicitExit(false);
Run Code Online (Sandbox Code Playgroud)

然后设置关闭事件

secondaryStage.setOnCloseRequest(event -> {
    // Your code here
});
Run Code Online (Sandbox Code Playgroud)

要制作系统托盘,请尝试以下代码:

原始文档链接: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.");
    }
Run Code Online (Sandbox Code Playgroud)

示例系统托盘图像:

系统托盘程序示例

要从 awt 事件处理程序调用 Javafx 的方法,您可以按照以下方式:

yourAwtObject.addActionListener(e -> {
    Platform.runLater(() -> primaryStage.show());
});
Run Code Online (Sandbox Code Playgroud)


小智 0

另外,如何确保当第一阶段关闭时,第二阶段也关闭?

当主阶段关闭时,您可以使用类似的方法来关闭辅助阶段:

primaryStage.setOnCloseRequest((WindowEvent we) -> {
    secondaryStage.close();
}
Run Code Online (Sandbox Code Playgroud)