This week's book giveaway is in the OCAJP 8 forum. We're giving away four copies of OCA Java SE 8 Programmer I Study Guide and have Edward Finegan & Robert Liguori on-line! See this thread for details.
hehe thanks for the reply, I worked out that I had forgotten to import awt maybe 2 mins before checking this thread. However I have another problem now...
My code has to switch from the title screen to the other section of the paintcomponent method when a key is pressed. Can anyone work out why it isnt?
Joined: May 21, 2008
By sticking in a bunch of System.out.println statements into all my methods to narrow where my error is. And ive worked out that the problem is that when I press a key, the keyPressed method isnt called at all. I cant seem to work out why.
KeyEvents always come from some source, most usually some sort of text field. A KeyListener receives KeyEvents from that source only after it has been registered to the source via the addKeyListener() method. A class that does not have this method most likely never issues key events, maning that it is somewhat unaware of keyboard imput. In your case, however, it's possible: A JPanel can receive keyboard interactions and has an addKeyListener() method - inherited from java.awt.Component, by the way. So you just have to add the KeyListener to your JPanel, in case of your (pretty un-clean) way of implementing JPanel and KeyListener in one class, this would be one line in your constructor: