How do you make menu item (JMenuItem) shortcut?

流过昼夜 提交于 2019-12-03 05:52:28
Dan D.

Example for CTRL + N.

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

Toolkit.getDefaultToolkit ().getMenuShortcutKeyMask() returns control key (ctrl) on Windows and linux, and command key (⌘) on Mac OS.

David Kroukamp

Simply create a KeyStroke and call setAccelerator(...) on the JMenuItem like so:

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
    }
}
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!