Move image using keyboard - Java

前端 未结 3 527
闹比i
闹比i 2020-12-21 01:49

I wanted to move my image using keyboard arrow keys. when I pressed the arrow keys it moves accordingly to the direction. However, I need to click on the image before able t

相关标签:
3条回答
  • 2020-12-21 02:21

    KeyListeners only work when the component which has the listener has focus. You are giving focus to what appears to be Collect by clicking on it. Then the listener works. You can add the listener to other things or force focus to remain on something like the outer frame by using a focus listener to regain focus whenever it is lost.

    0 讨论(0)
  • 2020-12-21 02:25

    You have look at KeyBindings, otherwise you have to JComponent#setFocusable() that nest the Image, example for Moving Image

    0 讨论(0)
  • 2020-12-21 02:38
    Collect.requestFocusInWindow();
    

    requestFocusInWindow()..

    Requests that this Component get the input focus, if this Component's top-level ancestor is already the focused Window.

    Make sure to call that only after the main window is visible and has the focus.

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