package com.github.hunter0x7c7.sync.utils; import com.github.hunter0x7c7.sync.model.interfaces.Callback; import com.github.hunter0x7c7.sync.model.storage.Session; import javafx.application.Platform; import javafx.stage.Stage; import javax.swing.*; import java.awt.*; import java.awt.event.ActionListener; import static com.github.hunter0x7c7.sync.model.global.Parameters.APPID; public class TrayUtil { private static TrayUtil mInstance; private TrayUtil() { } public static TrayUtil getInstance() { if (mInstance == null) { synchronized (TrayUtil.class) { if (mInstance == null) { mInstance = new TrayUtil(); } } } return mInstance; } public void addSystemTray(Stage primaryStage, String tooltip, String mipmap, MenuItem... items) { addSystemTray(primaryStage, tooltip, mipmap, null, items); } public void addSystemTray(Stage stage, String tooltip, String mipmap, Callback callback, MenuItem... items) { //检查系统是否支持托盘 if (!SystemTray.isSupported()) { //系统托盘不支持 return; } //执行stage.close()方法,窗口不直接退出 Platform.setImplicitExit(false); //弹出式菜单组件 MenuItem exit = new MenuItem("退出");//退出Exit final PopupMenu popup = new PopupMenu(); if (items != null) { for (MenuItem item : items) { if (item == null) continue; popup.add(item); } } popup.add(exit); //通过类加载器获取图像 ImageIcon imageIcon = new ImageIcon(ClassLoader.getSystemResource(mipmap));//"mipmap/ic_class_2_dex_tools_16.png" Image img = imageIcon.getImage(); TrayIcon trayIcon = new TrayIcon(img, tooltip, popup); //设置图标尺寸自动适应 //trayIcon.setImageAutoSize(true); trayIcon.setActionCommand(APPID); trayIcon.addActionListener(new ActionListener() { @Override public void actionPerformed(java.awt.event.ActionEvent e) { //鼠标双击系统托盘图标 Platform.runLater(new Runnable() { @Override public void run() { if (stage != null) { stage.show(); } } }); } }); //系统托盘 SystemTray tray = SystemTray.getSystemTray(); Platform.runLater(new Runnable() { @Override public void run() { try { tray.add(trayIcon); } catch (Exception e) { e.printStackTrace(); //系统托盘添加失败 } } }); //绑定系统托盘事件 exit.addActionListener(actionListener -> { if (callback != null) { callback.onCall(true); } if (tray != null) { tray.remove(trayIcon); } exitApp(); }); //点击关闭按钮时隐藏场景 stage.setOnCloseRequest(event -> { Platform.runLater(() -> { if (stage != null) { stage.hide(); } }); }); } //退出 public void exitApp() { //UI线程 Platform.runLater(new Runnable() { @Override public void run() { //退出前先关闭窗口 Stage stage = Session.getInstance().getPrimaryStage(); if (stage != null) { stage.close(); } //退出 Platform.exit(); } }); } }