java - 使用swing在java中为JButton创建热键

标签 java swing

我使用以下代码为使用 swing 的 java 表单创建热键。如果我按 ALT+N、ALT+R、ALT+1、ALT+2,光标将移动到正确的文本字段,然后我在相应的文本字段中输入值。它工作正常。我的问题是,我已经以这种形式保存并退出 JButtons。我按 CTRL+S 意味着将同时选择保存按钮如果我按 CTRL+X 意味着将选择退出按钮。如何为 JButton 创建助记符?如何使用以下代码执行 CTRL+S、CTRL+X?

提前致谢。

package hotkeys;
import java.awt.event.*;
import javax.swing.*;
import java.net.*;
public class hotkey extends JFrame {
    public static void main(String arg[]) {
        JLabel Name = new JLabel("Name");
        JTextField tf1 = new JTextField(20);
        Name.setLabelFor(tf1);
        Name.setDisplayedMnemonic('N');


        JLabel Regno = new JLabel("RegNO");
        JTextField tf2 = new JTextField(20);
        Regno.setLabelFor(tf2);
        Regno.setDisplayedMnemonic('R');

        JLabel Mark1 = new JLabel("Mark1");
        JTextField tf3 = new JTextField(20);
        Mark1.setLabelFor(tf3);
        Mark1.setDisplayedMnemonic('1');

        JLabel Mark2 = new JLabel("Mark2");
        JTextField tf4 = new JTextField(20);
        Mark2.setLabelFor(tf4);
        Mark2.setDisplayedMnemonic('2');


        JButton b1 = new JButton("Save");
        JButton b2 = new JButton("eXit");


        JFrame f = new JFrame();
        JPanel p = new JPanel();

        p.add(Name);
        p.add(tf1);
        p.add(Regno);
        p.add(tf2);
        p.add(Mark1);
        p.add(tf3);
        p.add(Mark2);
        p.add(tf4);
        p.add(b1);
        p.add(b2);

        f.add(p);
        f.setVisible(true);
        f.pack();
    }
}

最佳答案

您需要在按钮的组件输入映射中注册一个键绑定(bind)。在代码中(重复你在之前的问题中被告知要做的事情的微妙变体:-)

// create an Action doing what you want
Action action = new AbstractAction("doSomething") {

    @Override
    public void actionPerformed(ActionEvent e) {
        System.out.println("triggered the action");
    }

};
// configure the Action with the accelerator (aka: short cut)
action.putValue(Action.ACCELERATOR_KEY, KeyStroke.getKeyStroke("control S"));

// create a button, configured with the Action
JButton toolBarButton = new JButton(action);
// manually register the accelerator in the button's component input map
toolBarButton.getActionMap().put("myAction", action);
toolBarButton.getInputMap(JComponent.WHEN_IN_FOCUSED_WINDOW).put(
        (KeyStroke) action.getValue(Action.ACCELERATOR_KEY), "myAction");

关于java - 使用swing在java中为JButton创建热键,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8588145/

相关文章:

java - 如何解决这个没有为 Maven 上的构建指定目标?

Java 线程问题

java - 在 Java Swing 中构建 Jpeg 幻灯片

java - 如何在 Java 中更新此自定义绘制?

java - 如何在 Spring MVC 中创建多布局

java - 如何通过普通的 Java 套接字实现 (SSL/TLS) 安全通信

java - 将 Android 设备的壁纸保存为图片

使用 AES 和 MAC 进行 Java 加密

java - 使用 miglayout 的垂直按钮栏布局

java - 根据 JPanel 内部的组件调整其大小