Java Reference
In-Depth Information
We can now repeat these four steps to create and register the action listener with the
JButton exitB .
private class ExitButtonHandler implements ActionListener
{
public void actionPerformed(ActionEvent e)
{
System.exit(0);
}
}
The following statements create the action listener object for the button exitB :
ExitButtonHandler ebHandler;
ebHandler = new ExitButtonHandler();
exitB.addActionListener(ebHandler);
The interface ActionListener is contained in the package java.awt.event . There-
fore, to use this interface to handle events, your program must include the statement:
import java.awt.event.*;
or:
import java.awt.event.ActionListener;
The complete program to calculate the perimeter and area of a rectangle is:
//Given the length and width of a rectangle, this Java
//program determines its area and perimeter.
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
public class RectangleProgram extends JFrame
{
private JLabel lengthL, widthL, areaL, perimeterL;
private JTextField lengthTF, widthTF, areaTF, perimeterTF;
private JButton calculateB, exitB;
private CalculateButtonHandler cbHandler;
private ExitButtonHandler ebHandler;
private static final int WIDTH = 400;
private static final int HEIGHT = 300;
public RectangleProgram()
{
//Create the four labels
lengthL = new JLabel("Enter the length: ",
SwingConstants.RIGHT);
Search WWH ::




Custom Search