I am working a calculator using java swing and I want to be able to enter the numbers and operations via keyboard. I can\'t seem to get it working.
import java.
I think here is the problem:
button[0].getInputMap().put(...);
From JComponent.getInputMap() javadoc:
Returns the
InputMap
that is used when the component has focus. This is convenience method forgetInputMap(WHEN_FOCUSED)
.
So the button must have the focus to properly work. Since you're doing a calculator I'd suggest you use this instead:
button[0].getInputMap(JComponent.WHEN_IN_FOCUSED_WINDOW).put(...);
JComponent.getInputMap(int condition):
Returns the InputMap that is used during condition.
Parameters:
condition
- one ofWHEN_IN_FOCUSED_WINDOW
,WHEN_FOCUSED
,WHEN_ANCESTOR_OF_FOCUSED_COMPONENT