Keyboard Input with swing Java

后端 未结 1 1084
野的像风
野的像风 2021-01-21 01:38

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.         


        
相关标签:
1条回答
  • 2021-01-21 01:58

    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 for getInputMap(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 of WHEN_IN_FOCUSED_WINDOW, WHEN_FOCUSED, WHEN_ANCESTOR_OF_FOCUSED_COMPONENT

    0 讨论(0)
提交回复
热议问题