Learning Java
Custom Search

Previous Next

Set Up the Event Listener

To get our objects to respond to us, we will have to do the following:

  • Import the package that contains the event listener interfaces.
    import java.awt.event.*;
  • Have the class implement the event listener interface. The class will have to override all the methods contained in the interface. For example:
    public class CheckAction extends JFrame implements ActionListener {
  • Create the objects and add the event listener to them. The "this" refers to the class in which this code is found and that implements the listener.
    JButton   btn = new JButton("Push Me ");
    JCheckBox chk = new JCheckBox("Do you want a refund?");
    btn.addActionListener(this); chk.addActionListener(this);
  • Override the method that must respond to the event. If more than one object can cause this event, test to see which is the source of this occurrence.
        public void actionPerformed(ActionEvent evt) {
            Object source = evt.getSource();
            if (source == btn) {
    	    process button
    	} else if (source == chk) {
    	    process check box
    	} 
        }
    

 

Previous Next

Steps In Learning

Contact us

Copyright © 2008      N. Nelson      All Rights Reserved