Java setMnemonic() 并通过按键调用方法

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/24108974/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-14 10:11:49  来源:igfitidea点击:

setMnemonic() and call a method by pressing the key

javaswingkeypressedmnemonics

提问by Yithirash

I have to run a method() manually when pressing the key (Alt+H).

按下键 (Alt+H) 时,我必须手动运行 method()。

if("The key pressed==(Alt+H)"){
    callMethod();
}

public void callMethod(){
    //Some codes here
}

How I can actually do this in Java. Please give me a simple way to do this.

我如何在 Java 中真正做到这一点。请给我一个简单的方法来做到这一点。

采纳答案by Braj

It's worth reading here about Oracle Tutorial - Enabling Keyboard Operationwhere it is explained in details along with sample.

值得在此处阅读有关Oracle 教程 - 启用键盘操作的内容,其中详细解释了该教程并附有示例。

Read more about on Oracle Tutorial - How to Use Key Bindings

阅读有关Oracle 教程 - 如何使用键绑定的更多信息

Some example directly from the above tutorial:

直接来自上述教程的一些示例:

//Setting the mnemonic when constructing a menu item:
menuItem = new JMenuItem("A text-only menu item",
                     KeyEvent.VK_H);

//Setting the mnemonic after creation time:
menuItem.setMnemonic(KeyEvent.VK_H);

//Setting the accelerator:
menuItem.setAccelerator(KeyStroke.getKeyStroke(
    KeyEvent.VK_H, ActionEvent.ALT_MASK));


Read more here Oracle Tutorial - How to Use Buttons, Check Boxes, and Radio Buttons

在此处阅读更多内容Oracle 教程 - 如何使用按钮、复选框和单选按钮

Sample code: (Alt-Hwould click the Middle button)

示例代码:(Alt-H将单击中间按钮)

JButton b2 = new JButton("Middle button", middleButtonIcon);
b2.setMnemonic(KeyEvent.VK_H);

回答by tenorsax

If using menus then you can use setMnemonic(), see How to Use Menusfor examples. Another option is to use Key Bindings. For example:

如果使用菜单,则可以使用setMnemonic(),请参阅如何使用菜单以获取示例。另一种选择是使用Key Bindings。例如:

import java.awt.event.*;
import javax.swing.*;

public class TestKeys {
    private static void createAndShowGUI() {
        final JFrame frame = new JFrame("Keys");
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

        KeyStroke escapeKeyStroke = KeyStroke.getKeyStroke(KeyEvent.VK_H, InputEvent.ALT_MASK);

        Action testAction = new AbstractAction() {
            public void actionPerformed(ActionEvent e) {
                 JOptionPane.showMessageDialog(frame, "Alt-H pressed");
            }
        };

        frame.getRootPane().getInputMap(JComponent.WHEN_IN_FOCUSED_WINDOW).put(escapeKeyStroke, "TestAction");
        frame.getRootPane().getActionMap().put("TestAction", testAction);       

        JLabel label = new JLabel("Hit Alt-H");
        label.setBorder(BorderFactory.createEmptyBorder(20, 20, 20, 20));

        frame.add(label);
        frame.setLocationByPlatform(true);
        frame.pack();
        frame.setVisible(true);

    }

    public static void main(String args[]) {
        SwingUtilities.invokeLater(new Runnable() {
            public void run() {
                createAndShowGUI();
            }
        });
    }
}

回答by CodeSession

Best method is to use setMnemonic() because its the the simplest.

最好的方法是使用 setMnemonic() 因为它是最简单的。

check this article for more http://www.herongyang.com/Swing/JMenuBar-Set-Keyboard-Mnemonics-on-Menu-Items.html

查看这篇文章了解更多http://www.herongyang.com/Swing/JMenuBar-Set-Keyboard-Mnemonics-on-Menu-Items.html

private JMenu getColorMenu() {
  JMenu myMenu = new JMenu("Color");
  ButtonGroup myGroup = new ButtonGroup();

  JRadioButtonMenuItem myItem = new JRadioButtonMenuItem("Red");
  myItem.setSelected(true);
  myItem.setMnemonic(KeyEvent.VK_R);
  myItem.addActionListener(this);
  myItem.addMenuKeyListener(this);
  myGroup.add(myItem);
  myMenu.add(myItem);

  myItem = new JRadioButtonMenuItem("Green");
  myItem.setMnemonic(KeyEvent.VK_G);
  myItem.addActionListener(this);
  myItem.addMenuKeyListener(this);
  myGroup.add(myItem);
  myMenu.add(myItem);

  myItem = new JRadioButtonMenuItem("Blue");
  myItem.setMnemonic(KeyEvent.VK_B);
  myItem.addActionListener(this);
  myItem.addMenuKeyListener(this);
  myGroup.add(myItem);
  myMenu.add(myItem);

  return myMenu;