我很难在TrayIcon弹出菜单上创建快捷方式。
以下是我的代码。
final PopupMenu popup = new PopupMenu();
final TrayIcon trayIcon = new TrayIcon(createImage("images/bulb.gif", "tray icon"));
final SystemTray tray = SystemTray.getSystemTray();
//MenuItem aboutItem = new MenuItem("About", new MenuShortcut(KeyEvent.VK_A));
MenuItem aboutItem = new MenuItem("About", new MenuShortcut(KeyEvent.VK_A, false));
Menu settingMenu = new Menu("Settings");
MenuItem exitItem = new MenuItem("Exit");
popup.add(aboutItem);
popup.addSeparator();
popup.add(settingMenu);
popup.addSeparator();
popup.add(exitItem);
aboutItem.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
JOptionPane.showMessageDialog(null,
"This dialog box is run from the About menu item");
}
});
我坚持这一点。 当我按“a”键时,为什么我的程序不起作用? 我该如何正确使用? 我想在弹出菜单上表示一个短信键,例如下划线底部的'a'字符。
答案 0 :(得分:1)
以下是使用keyMnemonic和keyAccelerator的正确和更正的代码,它将放置在A
下的行 //Check the SystemTray support
if (!SystemTray.isSupported()) {
System.out.println("SystemTray is not supported");
return;
}
final PopupMenu popup = new PopupMenu();
final TrayIcon trayIcon =
new TrayIcon(createImage("images/bulb.gif", "tray icon"));
final SystemTray tray = SystemTray.getSystemTray();
// Create a popup menu components
MenuItem aboutItem = new MenuItem("About");
// Here is the change
aboutItem.setMnemonic(KeyEvent.VK_A);
aboutItem .setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_A,
0));
// end change
CheckboxMenuItem cb1 = new CheckboxMenuItem("Set auto size");
CheckboxMenuItem cb2 = new CheckboxMenuItem("Set tooltip");
Menu displayMenu = new Menu("Display");
MenuItem errorItem = new MenuItem("Error");
MenuItem warningItem = new MenuItem("Warning");
MenuItem infoItem = new MenuItem("Info");
MenuItem noneItem = new MenuItem("None");
MenuItem exitItem = new MenuItem("Exit");
//Add components to popup 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);
trayIcon.setPopupMenu(popup);
try {
tray.add(trayIcon);
} catch (AWTException e) {
System.out.println("TrayIcon could not be added.");
return;
}
希望这有用..
答案 1 :(得分:1)
例如http://www.javaswing.org/java-swing-popup-menu.aspx
private void showPopup(MouseEvent e) {