Java Reference
In-Depth Information
As explained earlier, by default, the content pane uses
BorderLayout
as its layout man-
ager, but for many applications,
FlowLayout
is more convenient. Recall that a flow layout
lays out components one row at a time, top to bottom. When one row is full, layout ad-
vances to the next row. Although this scheme gives you little control over the placement of
components, it is quite simple to use. However, be aware that if you resize the frame, the
position of the components will change.
After setting the size and the default close operation,
ButtonDemo( )
creates two but-
tons, as shown here:
The first button will contain the text "Up", and the second will contain "Down".
Next, the instance of
ButtonDemo
referred to via
this
is added as an action listener for
the buttons by these two lines:
This approach means that the object that creates the buttons will also receive notifications
when a button is pressed.
Each time a button is pressed, it generates an action event and all registered listeners are
notified by calling the
actionPerformed( )
method. The
ActionEvent
object representing
the button event is passed as a parameter. In the case of
ButtonDemo
, this event is passed
to this implementation of
actionPerformed( )
:
The event that occurred is passed via
ae
. Inside the method, the action command associ-
ated with the button that generated the event is obtained by calling
getActionCommand(
)
. (Recall that, by default, the action command is the same as the text displayed by the but-