Let's ignore that fact that you code is incomplete, so it's impossible to know what you are extending from or if you've actually added a KeyListener
.
KeyListener
is notorious for being fickle about it's focus state. Basically, this means, KeyListener
will only respond to keystrokes if the component it is registered to is focusable AND has keyboard focus...
A better solution would be to use the Key Bindings API, which provides better control over the focus level that will trigger key events.
You are also breaking the paint chain. Painting is a complex series of method calls, chaining together to produce the final result. By failing to call super.paint
, you've broken this chain, introducing the possibility of paint artifacts.
You should also avoid overriding paint
generally, but especially of top level containers, like windows, as they are not double buffered. It is recommended that instead, you extend from something JPanel
or JComponent
and override it's paintComponent
method instead.
Take a look at Performing Custom Painting for more details.
Updated based on seeing full source
- Avoid AWT based components (like
Applet
) the API is out of date and not many people use it any more, instead you should consider using aJApplet
instead. But personally, I would avoid applets until you have a better understanding of the overall API. - Don't call
setSize
within an applet, the size is determined by the html tag which describes the applet to the browser - Your
run
method is pointless as it doesn't actually do anything useful and may actually be causing your application to "hang" - Your
update
method is only painting thetrafficLight
BufferedImage
, but because you fail to callsuper.update
, nothing else is painted. It would be better to grid rid of it and do your painting in thepaint
method, but make sure you are callingsuper.paint
. But as I already said, you'd be better of using something likeJPanel
and overriding it'spaintComponent
method.
Take a look at Creating a GUI with Swing for more details
You may also find Why CS teachers should stop teaching Java applets of some worth...