My son (aged 11) who is learning Java is going to enter a question and some code. He tells me he has not been able to find the answer to this question on the site. You will
So GUI are event driven. Everything that occurs is driven by an event. A key press is an event. A component needs to listen for events, and do something when the event is fired. You can read more about how to write different listeners here. Some of the basic listeners are fairly easy to recognize (by name) like KeyListener
or MouseListener
. ActionListener
is also pretty common for button presses. You'll want to go through the tutorials and learn the different listeners.
Note though that with Swing there are focus issues with using a KeyListener
so it is preferred to use key bindings. As stated in the KeyListener
tutorial:
To define special reactions to particular keys, use key bindings instead of a key listener
A tutorial for key bindings can be found here and an example can been seen here. Here's the gif from the example, showing the movement of rectangle with a key press using key bindings
UPDATE just notice.
paint
method of JPanel
Never call repaint()
from inside a paint/paintComponent
method
public void paint() {//This is where the graphic is painted to the screen
repaint();
}
Get completely rid of the above code.