我们知道我们可以在setaccelerator()方法的帮助下调用菜单项,其中需要两次击键组合。如果我想通过一次击键调用一个菜单项...这里是我有点问题
menuitem=new JMenuItem("Delete");
menuitem.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_DELETE);
menu.add(menuitem);
请帮助.... !!
答案 0 :(得分:3)
查看How to Use Menus了解详情。下面是一个利用Action
定义加速器的示例。您还可以在菜单项上设置加速器,即:item.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_DELETE, 0));
。
import java.awt.Component;
import java.awt.Dimension;
import java.awt.event.ActionEvent;
import java.awt.event.KeyEvent;
import javax.swing.*;
public class MenuDemo {
public static void main(String[] args) {
javax.swing.SwingUtilities.invokeLater(new Runnable() {
@Override
public void run() {
final JFrame frame = new JFrame("Demo");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
JMenuBar menuBar = new JMenuBar();
JMenu menu = new JMenu("Menu");
menuBar.add(menu);
JMenuItem item = new JMenuItem(new TestAction(frame));
menu.add(item);
frame.setJMenuBar(menuBar);
frame.setSize(new Dimension(300, 300));
frame.setLocationByPlatform(true);
frame.setVisible(true);
}
});
}
static class TestAction extends AbstractAction {
private Component parent;
public TestAction(Component parent) {
super("Test");
this.parent = parent;
putValue(Action.ACCELERATOR_KEY,
KeyStroke.getKeyStroke(KeyEvent.VK_DELETE, 0));
}
@Override
public void actionPerformed(ActionEvent e) {
JOptionPane.showMessageDialog(parent, "Test");
}
}
}