Java keylistener and keybinding
I want to write a calculator and have a problem I have created an action listener for all buttons, and now I want to be able to enter data from the keyboard Do I need to finish the whole thing for keylistener or keybinding, or is there any other way to send it to the instruction in actionlistener after clicking the button? What's better: keylistener or keybinding
Solution
In general, if you have a limited set of key inputs, key binding is a better choice
Keylistener encounters problems related to focalization and other controls in the GUI, and the focus will always be away from components (using keylistener)
A simple solution is to use the actions API This allows you to define a self-contained "action", which acts as an actionlistener, but also with configuration information that can be used to configure other UI components, especially buttons
For example
Take a generic numberaction that can represent any number (now limit it to 0-9)
public class NumberAction extends AbstractAction { private int number; public NumberAction(int number) { putValue(NAME,String.valueOf(number)); } public int getNumber() { return number; } @Override public void actionPerformed(ActionEvent e) { int value = getNumber(); // Do something with the number... } }
What can you do
// Create the action... NumberAction number1Action = new NumberAction(1); // Create the button for number 1... JButton number1Button = new JButton(number1Action); InputMap im = getInputMap(WHEN_IN_FOCUSED_WINDOW); // Create a key mapping for number 1... im.put(Keystroke.getKeystroke(KeyEvent.VK_1,0),"number1"); im.put(Keystroke.getKeystroke(KeyEvent.VK_NUMPAD1,"number1"); ActionMap am = getActionMap(); // Make the input key to the action... am.put("number1",number1Action);
And you've finished
You can also create any number of numberaction instances for the same number, which means that you can configure the UI and binding separately, but know that when triggered, they will execute the same code logic, such as