img
Using Buttons
Perhaps the most widely used control is the push button. A push button is a component that
contains a label and that generates an event when it is pressed. Push buttons are objects of
type Button. Button defines these two constructors:
Button( ) throws HeadlessException
Button(String str) throws HeadlessException
The first version creates an empty button. The second creates a button that contains str as a label.
After a button has been created, you can set its label by calling setLabel( ). You can
retrieve its label by calling getLabel( ). These methods are as follows:
void setLabel(String str)
String getLabel( )
Here, str becomes the new label for the button.
Handling Buttons
Each time a button is pressed, an action event is generated. This is sent to any listeners that
previously registered an interest in receiving action event notifications from that component.
Each listener implements the ActionListener interface. That interface defines the
actionPerformed( ) method, which is called when an event occurs. An ActionEvent object
is supplied as the argument to this method. It contains both a reference to the button that
generated the event and a reference to the action command string associated with the button.
By default, the action command string is the label of the button. Usually, either the button
reference or the action command string can be used to identify the button. (You will soon
see examples of each approach.)
Here is an example that creates three buttons labeled "Yes", "No", and "Undecided".
Each time one is pressed, a message is displayed that reports which button has been
pressed. In this version, the action command of the button (which, by default, is its label)
is used to determine which button has been pressed. The label is obtained by calling the
getActionCommand( ) method on the ActionEvent object passed to actionPerformed( ).
// Demonstrate Buttons
import java.awt.*;
import java.awt.event.*;
import java.applet.*;
/*
<applet code="ButtonDemo" width=250 height=150>
</applet>
*/
public class ButtonDemo extends Applet implements ActionListener {
String msg = "";
Button yes, no, maybe;
public void init() {
yes = new Button("Yes");
Search WWH :
Custom Search
Previous Page
Java SE 6 Topic Index
Next Page
Java SE 6 Bookmarks
Home