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
There are at least three issues...
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
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.
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