The applet below demonstrates the basics of using the Button
component, and also a Label,
from the basic AWT framework.
The Applet
instance implements the ActionListener
interface so it must provide an actionPerformed()
method. The Button
and Label
instances are added to the Applet,
which inherits the Panel
class and its capability to hold other components. The default FlowLayout
will arrange the components sequentially left to right horizontally
and top to bottom vertically within the available space.
The button adds the Applet
instance to its list of ActionListeners
and ActionEvent
objects are sent to it via calls to the actionPerformed()
method.
ButtonApplet.java
|
import
java.awt.*;
import java.applet.*;
import java.awt.event.*;
/** This program demonstrates the Button and Label
* components in the basic AWT framework.
**/
public class ButtonApplet extends Applet
implements ActionListener
{
Label fLabel;
Button fButton;
int num_pushes;
/** Create the interface with a button. **/
public void init () {
num_pushes = 0;
add (fLabel = new Label ("Num Pushes
= 0"));
fLabel.setBackground (Color.blue);
fLabel.setForeground (Color.red);
// Create a Button and add it to
the Applet's panel.
add (fButton = new Button ("Push")
);
// Add this object to the buttons
ActionListener list.
fButton.addActionListener ( this
);
setBackground (Color.blue);
} // init
public void actionPerformed (ActionEvent
e) {
num_pushes++;
fLabel.setText ("Num Pushes = "
+ num_pushes);
} // actionPerformed
} // class ButtonApplet
|
Latest update: Nov. 4, 2004
|