1

我们知道我们可以在 setaccelerator() 方法的帮助下调用菜单项,其中需要两次击键的组合。如果我只想通过一个按键来调用菜单项怎么办...这是我遇到一点问题的地方

menuitem=new JMenuItem("Delete");
menuitem.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_DELETE);        
menu.add(menuitem);

请帮忙....!!

4

1 回答 1

3

查看如何使用菜单了解详细信息。下面是一个使用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");
        }
    }
}
于 2012-08-08T01:59:15.690 回答