java 托盘 实现二级菜单
package com.zs; import java.awt.AWTException; import java.awt.CheckboxMenuItem; import java.awt.Frame; import java.awt.Image; import java.awt.Menu; import java.awt.MenuItem; import java.awt.PopupMenu; import java.awt.SystemTray; import java.awt.Toolkit; import java.awt.TrayIcon; import java.awt.event.MouseAdapter; import java.awt.event.MouseEvent; import java.net.MalformedURLException; public class MyTaskTray { public static void main(String arg[]) throws MalformedURLException { final Frame frame = new Frame(""); frame.setUndecorated(true); // 检查系统托盘是否支持 if (!SystemTray.isSupported()) { System.out.println("系统托盘不支持"); return; } // 1.创建托盘图标 Image image = Toolkit.getDefaultToolkit().getImage( "view\\config\\resource\\ClientTrayIcon.jpg"); // 2.停留提示text String text = "停留此处提示"; // 创建弹出菜单 final PopupMenu popup = createPopupMenu(); final TrayIcon trayIcon = new TrayIcon(image, text, popup); final SystemTray tray = SystemTray.getSystemTray(); trayIcon.setPopupMenu(popup); trayIcon.addMouseListener(new MouseAdapter() { @Override public void mouseClicked(MouseEvent e) { if (e.getButton() == MouseEvent.BUTTON1) { frame.add(popup); popup.show(frame, e.getXOnScreen(), e.getYOnScreen()); } } }); try { frame.setResizable(false); frame.setVisible(true); tray.add(trayIcon); } catch (AWTException e) { System.out.println("异常:添加托盘图标失败"); } } protected static PopupMenu createPopupMenu() { final PopupMenu popup = new PopupMenu(); MenuItem aboutItem = new MenuItem("关于"); CheckboxMenuItem cb1 = new CheckboxMenuItem("设置1"); CheckboxMenuItem cb2 = new CheckboxMenuItem("设置2"); Menu displayMenu = new Menu("测试"); MenuItem errorItem = new MenuItem("测试4"); MenuItem warningItem = new MenuItem("测试3"); MenuItem infoItem = new MenuItem("测试2"); MenuItem noneItem = new MenuItem("测试1"); MenuItem exitItem = new MenuItem("退出"); // 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); return popup; } }
找了好久,发现中文资料没有这方面的例子( 也许自己搜的关键词不太对:) )。
如果在eclipse内直接运行,托盘图标中文出现乱码,解决办法:
在Arguments里的VM arguments添加如下配置
-Dfile.encoding=GBK