Thursday, June 25, 2009

How to use Key Bindings for some Swing components in a GUI

You have a Swing Application and you want to listen for some key actions, but only when some dialog or panel is active (on focus).
1.) Create a JPanel and move all needed components of user-dialog in it
2.)Create a global action for this Key

public class Myaction extends AbstractAction{

public void actionPerformed(ActionEvent e) {
System.out.println("Hello");}
}


3.)Instance the action


MyAction actions = new MyAction();



4.)Use the InputMap of JPanel to listen on e.g "F2" Key and put the instanced action
to its ActionMap.


jPanel1.getInputMap(JComponent.WHEN_ANCESTOR_OF_FOCUSED_COMPONENT).put(KeyStroke.getKeyStroke("F2"), "doSomething");

jPanel1.getActionMap().put("doSomething", actions);


Thats all. If you have an Swing application and the focus is on a JComponent in this Panel then the action will work.

0 comments:

Post a Comment