你如何制作菜单项(JMenuItem)的快捷方式?

时间:2012-11-13 18:48:01

标签: java swing shortcut jmenuitem

所以我注意到在awt中有一个MenuItem构造函数用于添加 CTRL +(某些键)快捷方式,但JMenuItem没有这样的构造函数。这样做的正确方法是什么?

我需要一个平等的awt:

MenuItem mi = new MenuItem("Copy", new MenuShortcut(KeyEvent.VK_C));

但是对于Swing。

2 个答案:

答案 0 :(得分:33)

CTRL + N 的示例。

menuItem.setAccelerator(KeyStroke.getKeyStroke('N', Toolkit.getDefaultToolkit ().getMenuShortcutKeyMask()));

Toolkit.getDefaultToolkit ().getMenuShortcutKeyMask()在Windows和Linux上返回控制键(ctrl),在Mac OS上返回命令键(⌘)。

答案 1 :(得分:9)

只需创建KeyStroke并在JMenuItem上致电setAccelerator(...),就像这样:

import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.InputEvent;
import java.awt.event.KeyEvent;
import javax.swing.JFrame;
import javax.swing.JMenu;
import javax.swing.JMenuBar;
import javax.swing.JMenuItem;
import javax.swing.KeyStroke;
import javax.swing.SwingUtilities;
import java.awt.Toolkit; 

public class Test {

    public Test() {
        initComponents();
    }

    public static void main(String[] args) {
        //create Swing components on EDT
        SwingUtilities.invokeLater(new Runnable() {
            @Override
            public void run() {
                new Test();
            }
        });
    }

    private void initComponents() {
        //create JFrame
        JFrame frame = new JFrame("Accelerator Sample");
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

        JMenuBar menuBar = new JMenuBar();//create menu bar to hold menus
        JMenu menu = new JMenu("File");//create a menu
        menuBar.add(menu);//add menu to bar

        JMenuItem menuItem = new JMenuItem("Say Hello");//create menu item

        //set shortcut CTRL+H (command+h on mac os)
        KeyStroke ctrlH = KeyStroke.getKeyStroke(KeyEvent.VK_H, Toolkit.getDefaultToolkit ().getMenuShortcutKeyMask());

        //set the accelerator
        menuItem.setAccelerator(ctrlH);
        //add listener which will be called when shortcut is pressed
        menuItem.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent actionEvent) {
                System.out.println("Hello, World");
            }
        });

        menu.add(menuItem);//add item to menu 'File'

        frame.setJMenuBar(menuBar);//set menubar of JFrame
        frame.pack();
        frame.setVisible(true);//set frame visible
    }
}