Java Reference
In-Depth Information
public void destroyApp(boolean unconditional) {
notifyDestroyed();
}
}
After the implementation of the ProgressBar , we will now focus on an active component that is
capable of handling user events. In order to show how this can be achieved, we will implement a button
that displays an image instead of a text label. When the button is pressed by tapping the stylus on it, it
will create an ActionEvent and send it to all registered listeners.
As in the ProgressBar implementation, we derive our ImageButton component from the
Component class. Listing 4.8 contains the source code of the ImageButton . The paint() ,
getPreferredSize() , and getMinimumSize() methods correspond to their counterparts of
the ProgressBar implementation. The constructor takes an image object and a command string and
stores the parameters in object variables.
For handling user input, one possibility would be to register a mouse listener. However, for custom
components, it is more appropriate to overwrite the processMouseEvent() method, which
receives all mouse events when enabled. Enabling the events roughly corresponds to the registration
process of the listener interface. This is done by calling the enableEvents() method of the
Component class with the parameter AWTEvent.MOUSE_EVENT_MASK . Without this call, our
implemented processMouseEvent() method would never be called by the event handler.
In addition to handling mouse events, it is necessary to enable users of the component to register action
listeners, just like for regular buttons. Thus, the methods addActionListener() and
removeActionListener() must be provided. The listeners variable contains a Vector that
keeps track of the listeners registered with the ImageButton component.
In the processMouseEvent() method, a check for the event ID MOUSE_CLICKED is performed.
If the mouse event passes the test, an ActionEvent object is created and sent to the
actionPerformed() methods of all registered listeners by iterating through the listeners.
Listing 4.8 ImageButton.java
import java.awt.*;
import java.awt.event.*;
import java.util.Vector;
public class ImageButton extends Component {
Image image;
String command;
Vector listeners = new Vector();
public ImageButton (Image image, String command) {
this.image = image;
this.command = command;
enableEvents(AWTEvent.MOUSE_EVENT_MASK);
}
public void addActionListener(ActionListener listener) {
listeners.addElement (listener);
}
 
Search WWH ::




Custom Search