- Okay, let's try a simple example of
using events. Try to create a program which will respond to
button events. In the following example, a panel is colored
differently each time the user clicks the button:
import java.awt.*;
public class EventExample extends Panel
{
public Panel displayPanel;
public Button colorButton;
public Color[] colors = {Color.black,
Color.red,
Color.yellow,
Color.green}; private int counter = 0;
public EventExample()
{
setLayout(new BorderLayout());
displayPanel = new Panel();
add("Center", displayPanel);
colorButton = new Button("Change Color");
add("South", colorButton);
}
public static void main(String[] args)
{
Frame baseFrame = new Frame();
EventExample ee = new EventExample();
baseFrame.add("Center", ee);
baseFrame.reshape(10,10,200,200);
baseFrame.setTitle("Event Example");
baseFrame.show();
}
public boolean action(Event evt, Object obj)
{
displayPanel.setBackground(colors[counter]);
if (counter <=2)
counter++;
else
counter =0;
return super.action(evt, obj);
}
}
Previous Page |
Next Page
|