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.

Leave a comment