Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
449 views
in Technique[技术] by (71.8m points)

java - Shortcut key for jButton without using alt key

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.

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

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
}
});
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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 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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...