HOW TO BIND KEYS TO CONTROLS IN JAVA

This is a simple method to bind keys to controls in java. Sometimes you may also want to change the way by default a control respond to a key press. For example when the “Enter” is pressed it navigates through the rows and column but if you want to change this behavior then you are at the correct place.

Below is a simple method to get you through.

private void tbProductKeypress() {

tbProducts.getInputMap().put(KeyStroke.getKeyStroke(KeyEvent.VK_ENTER, 0),"check1");

tbProducts.getActionMap().put("check1", new AbstractAction() {

public void actionPerformed(ActionEvent e) {

//add your code here

}

});

}

Note:This method is added after the control has been created. Also tbProducts is the name of the JTable (control) to bind the key to.

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s