Java Reference
In-Depth Information
User Interaction and Event Handling
The original ComponentSample MIDlet doesn't allow user interaction. However, some kind of exit
button would be useful. Buttons are represented by the component class Button . The only parameter
of the constructor is the button label text. The following lines add a button to the south area of the
frame (the layout areas will be described in more detail in the next section):
Button b = new Button ("Exit");
frame.add(b, BorderLayout.SOUTH);
When the program is started with the additional lines, a button will appear at the bottom of the Frame ,
but nothing will happen when the button is clicked. The button still needs to be linked to the desired
action, in this case leaving the program. In AWT, all kinds of user interface interactions—like clicking
a button—are represented by event objects. In the case of a Button , the corresponding event object is
an instance of ActionEvent . If an application is interested in some kind of event, it must implement
the corresponding listener interface, containing one or more callback methods. For ActionEvent s,
the listener interface is
public interface ActionListener {
public void actionPerformed (ActionEvent e);
}
Both the event classes and listener interfaces are contained in the package java.awt.event .
In order to handle events, an object implementing the listener interface must be registered with the
component that is the source of the events. For registering an action listener, the button class provides
the method addActionListener(ActionListener l) .
In order to keep your sample program simple, you can add the actionPerformed() method to the
MIDlet class directly and thus let it implement the ActionListener interface (see Listing 4.2 ) .
Listing 4.2 ComponentSample2.java —Enhanced Version of the ComponentSample
Handling User Interaction
import java.awt.*;
import java.awt.event.*;
import javax.microedition.midlet.*;
public class ComponentSample2 extends MIDlet implements
ActionListener {
Frame frame;
public ComponentSample2() {
frame = new Frame ("Hello World");
frame.add(new Label ("Hello World"));
Button b = new Button ("Exit");
b.addActionListener(this);
frame.add(b, BorderLayout.SOUTH);
}
public void actionPerformed(ActionEvent ae) {
frame.dispose();
notifyDestroyed();
}
public void startApp() {
frame.show();
}
 
Search WWH ::




Custom Search