Java Reference
In-Depth Information
}
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
public void run() {
new ActionListenerExample();
}
});
}
}
This is much better. There is, however, also another mechanism by which you can determine
the correct action to take whenever an event is fired, that is by means of a so‐called action com-
mand. This is especially useful when the same event source can lead to different behavior. The
following example shows how action commands work. Pay particular attention to the use of the
setActionCommand and getActionCommand methods.
import java.awt.Color;
import java.awt.FlowLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.SwingUtilities;
public class DiscoLightsExample extends JFrame implements ActionListener {
private final String ACTION_ON = "LIGHT ON";
private final String ACTION_OFF = "LIGHT OFF";
private final String ACTION_CYCLE = "CYCLE COLOR";
private final Color[] COLORS = new Color[]{
Color.white,
Color.green,
Color.red,
Color.yellow,
Color.orange,
Color.pink
};
private int currentColor = 0;
private boolean isLightOn = false;
public DiscoLightsExample() {
setTitle("Disco Light Party Frame");
setLayout(new FlowLayout());
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
JButton btnOffOn = new JButton("Lights On");
JButton btnColor = new JButton("Cycle Color");
btnOffOn.setActionCommand(ACTION_ON);
btnColor.setActionCommand(ACTION_CYCLE);
btnOffOn.addActionListener(this);
Search WWH ::




Custom Search