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.

Friday, June 19, 2009

How to use Netbeans Progress bar

Package org.netbeans.api.progress Description
This API allows to visualize tracking for progress of long lasting tasks.

The usual usecase goes like this:



ProgressHandle handle = ProgressHandleFactory.createHandle("My custom task");
...
// we have 100 workunits
// at this point the task appears in status bar.
handle.start(100);
...
handle.progress(10);
...
handle.progress(50);
...
// at this point the task is finished and removed from status bar
handle.finish();


http://bits.netbeans.org/dev/javadoc/org-netbeans-api-progress/org/netbeans/api/progress/package-summary.html