不使用alt键的jButton的快捷键 [英] Shortcut key for jButton without using alt key

查看:320
本文介绍了不使用alt键的jButton的快捷键的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在SWT中,只需在按钮标签中的字母前添加& 即可为任何按钮提供快捷键。例如,如果我的按钮标签是& Play ,我可以通过在键盘上按字母 p 来激活按钮。

In SWT you can give any button a shortcut key simply by adding & in front of the letter in the button label. For example, if my button label is &Play, I can activate the button by hitting letter p on the keyboard.

在Swing中,您可以使用助记符属性添加快捷键。但是,您需要按 alt + p 来激活该按钮。这非常适合菜单快捷方式。我想用字母按下并没有alt修饰符激活按钮。

In Swing, you can add a shortcut key using the mnemonic property. However, you need to hit alt+p to activate the button. This is really most appropriate for menu shortcuts. I want to activate the button with a letter press and no alt modifier.

我看过这篇关于如何做的帖子,但看起来很荒谬。有没有更简单的方法呢?

I've seen this post on how to do it, but it seems absurdly complicated. Is there an easier way to do this?

http://linuxjavaprogrammer.blogspot.com/2008/01/java-swing-jbutton-keyboard-shortcuts.html

更新:在@camickr建议之后,我最终使用了此代码。我在网上找不到任何清晰简单的例子,所以希望这会帮助别人。

Update: After @camickr suggestion, I ended up using this code. I couldn't find any clear and simple example online, so hopefully this will help people out.

// play is a jButton but can be any component in the window
play.getInputMap(play.WHEN_IN_FOCUSED_WINDOW).put(KeyStroke.getKeyStroke(KeyEvent.VK_P, 0), "play");
play.getActionMap().put("play", new AbstractAction() {
public void actionPerformed(ActionEvent e) {
  playActionPerformed(e);  // some function
}
});


推荐答案

是的,Swing旨在使用键绑定。因此,不是向按钮添加ActionListener,而是添加Action。然后可以通过按钮或菜单项共享该Action。您还可以使用KeyBindings分配任意数量的KeyStrokes来调用Action。本教程还有一个关于Actions的部分,解释了为什么使用Action是有益的。

Yes, Swing was designed to use Key Bindings. So instead of adding an ActionListener to the button you add an Action. Then that Action can be shared by the button or a menu item. You can also assign any number of KeyStrokes to invoke the Action by using the KeyBindings. The tutorial also has a section on Actions which explains why using an Action is beneficial.

JComponent有一个registerKeyboardAction(...)方法,它基本上用于输入InputMap / ActionMap绑定对你而言,它还必须将ActionListener包装在一个包装器Action中,因此你最好自己绑定它。

JComponent has a registerKeyboardAction(...) method which basically does the InputMap/ActionMap bindings for you, but it also has to wrap the ActionListener in a wrapper Action so its preferrable for you to do you own bindings.

这篇关于不使用alt键的jButton的快捷键的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆