我使用以下代码创建了一个非常简单的托盘菜单:
final Frame frame = new Frame("");
frame.setUndecorated(true);
// Check the SystemTray is supported
if (!SystemTray.isSupported()) {
System.out.println("SystemTray is not supported");
return;
}
final TrayIcon trayIcon = new TrayIcon(Toolkit.getDefaultToolkit().getImage(
new URL("http://url.com/trayIcon.png")), "Library Drop");
final SystemTray tray = SystemTray.getSystemTray();
// Create a pop-up menu components
final PopupMenu popup = createPopupMenu();
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("TrayIcon could not be added.");
}
} catch (MalformedURLException ex) {
Logger.getLogger(Client.class.getName()).log(Level.SEVERE, null, ex);
}
protected static PopupMenu createPopupMenu() {
final PopupMenu popup = new PopupMenu();
MenuItem aboutItem = new MenuItem("Accept");
MenuItem aboutItem1 = new MenuItem("Dont accept");
MenuItem aboutItem2 = new MenuItem("Quit");
// Add components to pop-up menu
popup.add(aboutItem);
popup.add(aboutItem1);
popup.addSeparator();
popup.add(aboutItem2);
return popup;
}
我如何聆听和检查用户何时选择“接受”、“不接受”等?
另外由于某种原因,trayIcon 上的高度最大,我怎样才能告诉托盘图标恰好是 X 乘 Y 像素?
编辑:高度/宽度问题仅在 Mac 中,在 Windows 上工作正常