Java Reference
In-Depth Information
private
JButton exitB, appendB;
exitB =
new
JButton("Exit");
appendB =
new
JButton("Append");
Container pane = getContentPane();
pane.add(headingL);
pane.add(lineTF);
pane.add(whiteBoardTA);
pane.add(appendB);
pane.add(exitB);
We will specify the sizes and locations of the GUI components when we write the
complete program.
In Chapter 6, action listener interfaces are implemented through inner classes. As
explained in Chapter 10, any class containing the application can directly implement
the
interface
ActionListener
. The GUI programs of this chapter directly implement
the interfaces to handle events. Suppose
WhiteBoard
is the name of the class to imple-
ment the application to create the preceding GUI. Then, the heading of this class is:
public class
WhiteBoard
extends
JFrame
implements
ActionListener
The method
actionPerformed
is included as a member of the
class
WhiteBoard
.To
register the action listener with
exitB
, all you need to do is include the following
statement in the program:
exitB.addActionListener(
this
);
Of course, the necessary code is placed in the method
actionPerformed
.
Because action events are generated by the two buttons, the method
actionPerformed
uses the methods
getActionCommand
and
equals
to identify the source of the event.
The definition of this method is:
public void
actionPerformed(ActionEvent e)
{
if
(e.getActionCommand().equals("Append"))
//Line 1
whiteBoardTA.append(lineTF.getText());
//Line 2
else if
(e.getActionCommand().equals("Exit"))
//Line 3
System.exit(0);
//Line 4
}
If the user clicks the
Append
button, the
if
statement in Line 1 evaluates to
true
.Inthiscase,
the statement in Line 2 retrieves the line of text from the text field object
lineTF
and appends
it to the text in the text area object
whiteBoardTA
. When the user clicks the
Exit
button, the
if
statement in Line 3 evaluates to
true
and the statement in Line 4 terminates the program.
The complete program listing follows:
import
javax.swing.*;
import
java.awt.*;
import
java.awt.event.*;
Search WWH ::
Custom Search