Java Reference
In-Depth Information
The buttons
calculateB
and
exitB
can be placed into the container
pane
by using the
method
add
. The following statements add these buttons to the
pane
:
pane.add(calculateB);
pane.add(exitB);
Now you have two more objects in the container, so you need to modify the
GridLayout
to accommodate five rows and two columns, and then add all the compo-
nents. The following statements create the required grid layout and add the labels, text
fields, and buttons to the container
pane
:
pane.setLayout(
new
GridLayout(5,2));
//specify the layout
pane.add(lengthL);
//add the label lengthL
pane.add(lengthTF);
//add the text field lengthTF
pane.add(widthL);
//add the label widthL
pane.add(widthTF);
//add the text field widthTF
pane.add(areaL);
//add the label areaL
pane.add(areaTF);
//add the text field areaTF
pane.add(perimeterL);
//add the label perimeterL
pane.add(perimeterTF);
//add the text field perimeterTF
pane.add(calculateB);
//add the button calculateB
pane.add(exitB);
//add the button exitB
Notice that the preceding
add
statements place the components from left to right and
from top to bottom.
HANDLING AN EVENT
You have now learned how to create a window, how to create a container, and how to
create labels, text fields, and buttons.
Now that you can create a button, such as
calculateB
, you need to specify how such
a button should behave when you click it. For example, when you click the button
calculateB
, you want the program to calculate the area and perimeter of the
rectangle and display these values in their respective text fields. Similarly, when you
click the button
exitB
, the program should terminate.
Clicking a
JButton
creates an event, known as an action event, which sends a
message to another object, known as an action listener. When the listener receives
the message, it performs some action. Sending a message or an event to a listener
object simply means that some method in the listener object is invoked with the
event as the argument. This invocation happens automatically; you will not see the
code corresponding to the method invocation. However, you must specify two
things:
Search WWH ::
Custom Search