You should really go back and really figure out your games graphical architecture.
Most Java novices tend to start with Graphics2D (which you are already using). However, you’ve fallen into a “trap” of sorts that I see a lot of people fall into. You do not have a gameloop. You have your game logic only work once a key is pressed. While this works on a very small scale, it will cause you problems down the road.
I would set up my application this way:
-
Main Class which creates my own screen for drawing
-
Screen class (extends JPanel) like you have
[list][li]Needs to have a subclass (or can be combined with the screen) which implements Runnable[list][li]This is to control your games “FPS”[/li]
[/list][/li]
-
Game Class[li]This is to control your games logic. If you want, you can tie it in directly with the screen (in the same thread), or you can attempt multithreading.[/li]
[/list]
Using this style of architecture, you can change the color of the rectangle (via keypress) in the game class, and then on the next redraw, the screen class will show it’s new color. This way, you do not have to redraw the game every time a key is pressed, and therefore have your application run with more consistency.