Lesson 6:


Events

  1. Every mouse move, click, keystroke, button push, etc. generates an event.
  2. Any component can be the source of an event.
  3. Any class can be a listener for an event by using the appropriate interface.  So a class that "listens" for button pushes would use the ActionListener interface.
  4. A class is registered with the source as the one who is listening for a particular type of event.
     

Try this:

  1. Take a look at the file Lesson6.java from the web page.  When you try it out, you will want to run the applet using a web browser so you can see the Java console.  The Java console can be made visible in IE by selecting it under the Tools menu
    Locate the code in the applet that creates and registers a listener for the button pushes.
  2. Change the code so that the applet listens to its action events rather than creating a new class to do this.  (You will want to use the keyword this.)
  3. Change the code so that there are now two buttons and a label and the applet prints a different message depending on which button is pushed.  (To do this you need to change the actionPerformed method so that it checks the ActionEvent e to determine which button produced the event. Look up the getSource() method for the ActionEvent class.  This should return the Object which produced the action. )
  4. Modify the applet so that it is also a "MouseListener".  Look up the MouseListener interface in your documentation and see if you can make the applet print a message every time you click the mouse.  The source of the events will be the applet so be sure you register this!