javafx系统托盘使用的awt的系统托盘组件来进行制作的,其中的Image、PopupMenu、MenuItem、TrayIcon、SystemTray等组件均为awt组件。
注意:使用前要加入该参数System.setProperty("java.awt.headless", "false");防止出现awt headless异常
private final static String title="系统";
private void systemTray(Stage primaryStage) {
try {
//设置为false时点击关闭按钮程序不会退出
Platform.setImplicitExit(false);
//加载系统托盘图标
ClassPathResource trayClassPathResource = new ClassPathResource("images" + File.separator + "tray.png");
URL url = trayClassPathResource.getURL();
//使用awt的组件制作系统托盘按钮
java.awt.Image image = Toolkit.getDefaultToolkit().getImage(url);
PopupMenu trayMenu = new PopupMenu();
MenuItem show = new MenuItem("显示");
MenuItem exit = new MenuItem("退出");
trayMenu.add(show);
trayMenu.add(exit);
//加载系统托盘组件
TrayIcon trayIcon = new TrayIcon(image, title, trayMenu);
//系统托盘图片自适应
trayIcon.setImageAutoSize(true);
//将系统托盘组件加载到系统托盘中
SystemTray systemTray = SystemTray.getSystemTray();
systemTray.add(trayIcon);
//绑定系统托盘事件
show.addActionListener(actionListener -> {
Platform.runLater(() -> primaryStage.show());
});
exit.addActionListener(actionListener -> {
stop();
});
//点击关闭按钮时隐藏场景
primaryStage.setOnCloseRequest(windowEvent -> {
primaryStage.hide();
});
} catch (Exception e) {
e.printStackTrace();
}
}