How to use KeyListener with JFrame?

后端 未结 4 1707
萌比男神i
萌比男神i 2020-11-30 14:42

So, I was trying to make a rectangle move with a KeyEvent (KeyListener) and whenever I try to hit the key, the rectangle doesn\'t move.

The

4条回答
  •  离开以前
    2020-11-30 15:37

    There are at least three issues...

    Firstly...

    Your mainFrame class extends from JFrame, but in your main method, you create an instance of it and ignore it, by creating your own JFrame.

    The KeyListener is registered to the instance of mainFrame, meaning, it's been ignored.

    You should get rid of extends JFrame as it's just confusing the issue

    Secondly...

    KeyListener will only respond to key events when the component it is registered to is focusable AND has direct focus, this makes it unreliable.

    Instead, you should use the key bindings API with the Draw panel, this will allow you to over come the focus issues.

    Thirdly...

    You've broken the paint chain, this means that when the rectangle moves, what was painted previously will still remain.

    You should refrain from overriding paint and instead use paintComponent. There are lots of reasons for this, but generally, it paints in the background, is called as updates to child components.

    Finally, make sure you are calling super.paintComponent before you do anything else, to ensure the Graphics context is prepared for painting

    Take a look at Performing Custom Painting for more details

提交回复
热议问题