107 lines
3.6 KiB
Java
107 lines
3.6 KiB
Java
package org.aohe.show;
|
||
|
||
import cn.hutool.core.io.resource.ResourceUtil;
|
||
import org.aohe.constant.SocketEnum;
|
||
import org.aohe.web.SocketUtils;
|
||
|
||
import javax.swing.*;
|
||
import java.awt.*;
|
||
|
||
public class TrayFrame {
|
||
|
||
public void create() throws Exception {
|
||
//创建Socket连接,默认是执行了start操作
|
||
SocketUtils.start(SocketEnum.SCAN_SOCKET);
|
||
|
||
// 确保事件调度线程(EDT)创建和显示GUI
|
||
SwingUtilities.invokeLater(() -> {
|
||
// 检查系统是否支持系统托盘
|
||
if (!SystemTray.isSupported()) {
|
||
System.out.println("系统托盘不被支持");
|
||
return;
|
||
}
|
||
|
||
// 获取系统托盘实例
|
||
SystemTray tray = SystemTray.getSystemTray();
|
||
|
||
// 创建一个图像,作为托盘图标
|
||
|
||
Image image = Toolkit.getDefaultToolkit().getImage(ResourceUtil.getResource("ah.png").getFile());
|
||
|
||
// 创建一个弹出菜单
|
||
PopupMenu popup = new PopupMenu();
|
||
|
||
// 创建菜单项
|
||
MenuItem aboutItem = new MenuItem("About");
|
||
//CheckboxMenuItem cb1 = new CheckboxMenuItem("Enable Message"); // 使用CheckboxMenuItem替换JCheckBoxMenuItem
|
||
MenuItem exitItem = new MenuItem("Exit");
|
||
MenuItem startServiceItem = new MenuItem("Start Service");
|
||
MenuItem stopServiceItem = new MenuItem("Stop Service");
|
||
|
||
// 初始化按钮状态
|
||
startServiceItem.setEnabled(false);
|
||
stopServiceItem.setEnabled(true);
|
||
|
||
// 将菜单项添加到弹出菜单
|
||
popup.add(aboutItem);
|
||
//popup.add(cb1);
|
||
popup.addSeparator();
|
||
popup.add(startServiceItem);
|
||
popup.add(stopServiceItem);
|
||
popup.addSeparator();
|
||
popup.add(exitItem);
|
||
|
||
// 创建托盘图标
|
||
TrayIcon trayIcon = new TrayIcon(image, "Scan Tray Program", popup);
|
||
|
||
// 设置托盘图标大小
|
||
trayIcon.setImageAutoSize(true);
|
||
|
||
// 添加托盘图标到系统托盘
|
||
try {
|
||
tray.add(trayIcon);
|
||
} catch (AWTException e) {
|
||
System.out.println("无法添加托盘图标");
|
||
return;
|
||
}
|
||
|
||
// 添加事件监听器
|
||
aboutItem.addActionListener(e -> JOptionPane.showMessageDialog(null, "AoHe 的扫描托盘程序"));
|
||
|
||
// cb1.addItemListener(e -> {
|
||
// if (cb1.getState()) {
|
||
// System.out.println("通知已启用");
|
||
// } else {
|
||
// System.out.println("通知已禁用");
|
||
// }
|
||
// });
|
||
|
||
startServiceItem.addActionListener(e -> {
|
||
try {
|
||
SocketUtils.start(SocketEnum.SCAN_SOCKET);
|
||
} catch (Exception ex) {
|
||
throw new RuntimeException(ex);
|
||
}
|
||
startServiceItem.setEnabled(false);
|
||
stopServiceItem.setEnabled(true);
|
||
System.out.println("服务已启动");
|
||
});
|
||
|
||
stopServiceItem.addActionListener(e -> {
|
||
SocketUtils.safeStop(SocketEnum.SCAN_SOCKET);
|
||
startServiceItem.setEnabled(true);
|
||
stopServiceItem.setEnabled(false);
|
||
System.out.println("服务已停止");
|
||
});
|
||
|
||
exitItem.addActionListener(e -> {
|
||
tray.remove(trayIcon);
|
||
SocketUtils.safeStop(SocketEnum.SCAN_SOCKET);
|
||
System.exit(0);
|
||
});
|
||
});
|
||
}
|
||
|
||
}
|
||
|