![]() |
|||||||||||||
Tutorial |
|||||||||||||
EventHandling using the new Java - APISince I got many mails that had to do with compilation warnings due to the deprecated event handling I use within the example applets I decided to write this little chapter about the newer, non deprecated version of the event handling. But the other two chapters about mouse and keyboard event handling will still be available, because on the one hand they go maybe a little bit more into the details than this one will and I still think that the eventhandlin methods I describe there might be easier to understand for an unexperienced programmer. KeyListenerTo handle keyboard events you'll find in the package java.awt.event a interface named KeyListener . If you want your applet to handle keyboard events your applet should implement this interface or use a class that implements it. This interface forces you to implement the following methods (names should be self explaining ;-):
To allow the applet to listen to keyboard events you have to register the KeyListener class with the applet. This happens by calling the addKeyListener(KeyListener listener) method in the init() - method of the applet class. If the applet implements the interface on its own, just write addKeyListener(this) . More information about the actual key event (which key was pressed...) is available through the KeyEvent instance that comes with the call of the corresponding Listener method. You can find some examples of how to get those detail information of the key event in the example source code to this chapter. Mouse eventsMouse events are handeled quite the same way as key events with just one exception. There are two different listener interfaces for mouse events(also within the package java.awt.event) which are MouseListener and MouseMotionListener . Both have to be added to the applet exactly the same way as key events if the applet should be able to listen to mouse clicks and mouse move events. To add the listeners to the applet just use the methods addMouseListener(MouseListener listener) and addMouseMotionListener(MouseMotionListener listener) . In details the following methods must be implemented by the listener classes, the names are again self explaining: MouseListener
MouseMotionListener
Please find details of the information you can get out of the MouseEvent if you take a look at the example applet class to this chapter. SourceCode download Next ChapterThe first game |
|||||||||||||
|
|
|||||||||||||