【问题标题】:Windowbuilder shortcut key窗口生成器快捷键
【发布时间】:2014-03-07 18:09:54
【问题描述】:

如何创建带有快捷键的按钮?

结果将在按钮标签或控件上显示带下划线的字母。 然后用户可以按[Alt]+键运行控件的默认actionEvent

提前谢谢你。

【问题讨论】:

  • 你尝试了什么?你谷歌了吗?
  • 我试图查看所有控件的属性但没有成功。在互联网上,我发现了一些与 actionMap 相关的东西。我看起来很复杂。这就是为什么我想知道是否有更简单的选择。在其他语言中,您只需将“&”前缀添加到标题中所需的字母。

标签: java swing key-bindings windowbuilder


【解决方案1】:

“我发现了一些与 actionMap 相关的东西。我看起来很复杂。”

一点也不复杂。您要做的是使用Action(与带有回调的ActionListener相似),它可以分配给不同的组件。您可以将相同的Action 用于JPanel JButton

假设你有这个Action

Action printHelloAction = new AbstractAction("Print") {
    public void actionPerformed(ActionEvent e) {
        System.out.println("Hello");
    }
};

您要做的是将其添加到JPanelActionMapInputMap同时只需将Action 添加到JButton

JPanel panel = new JPanel();
InputMap im = panel.getInputMap(JComponent.WHEN_IN_FOCUSED_WINDOW);
im.put(KeyStroke.getKeyStroke(KeyEvent.VK_P, ActionEvent.CTRL_MASK), "printAction");
ActionMap am = panel.getActionMap();
am.put("printAction", printHelloAction);    // add to JPanel ActionMap

JButton button = new JButton(printHelloAction); // add to JButton
button.setText("Print Hello");

您可以看到我对JPanel 键绑定和JButton 使用了相同的Action

查看更多 How to use ActionHow to Use Key Bindings


这是上面代码中的一个示例。使用 Ctrl + P

import java.awt.event.ActionEvent;
import java.awt.event.KeyEvent;
import javax.swing.AbstractAction;
import javax.swing.Action;
import javax.swing.ActionMap;
import javax.swing.InputMap;
import javax.swing.JButton;
import javax.swing.JComponent;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.KeyStroke;
import javax.swing.SwingUtilities;

public class KeyBindActionDemo {

    public KeyBindActionDemo() {
        Action printHelloAction = new AbstractAction("Print") {
            public void actionPerformed(ActionEvent e) {
                System.out.println("Hello");
            }
        };
        JPanel panel = new JPanel();
        InputMap im = panel.getInputMap(JComponent.WHEN_IN_FOCUSED_WINDOW);
        im.put(KeyStroke.getKeyStroke(KeyEvent.VK_P, ActionEvent.CTRL_MASK), "printAction");
        ActionMap am = panel.getActionMap();
        am.put("printAction", printHelloAction);

        JButton button = new JButton(printHelloAction);
        button.setText("Print Hello");

        panel.add(button);

        JFrame frame = new JFrame();
        frame.add(panel);
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        frame.pack();
        frame.setLocationRelativeTo(null);
        frame.setVisible(true);
    }

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

【讨论】:

  • 感谢 Peeskillet 的解释和代码示例。我真的很感谢你的帮助!问候
猜你喜欢
  • 2012-01-28
  • 1970-01-01
  • 1970-01-01
  • 2013-06-29
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多