Java Reference
In-Depth Information
controlPane.add(button = new JButton("Lucky Numbers!"));
button.setBorder(BorderFactory.createRaisedBevelBorder());
button.addActionListener(new
HandleControlButton(PICK_LUCKY_NUMBERS));
button.setPreferredSize(buttonSize);
controlPane.add(button = new JButton("Color"));
button.setBorder(BorderFactory.createRaisedBevelBorder());
button.addActionListener(new HandleControlButton(COLOR));
button.setPreferredSize(buttonSize);
content.add(controlPane);
}
Directory "Lottery 1"
How It Works
You create another JPanel object to hold the control buttons and just to show that you can, you pass a
layout manager object to the constructor. It's a FlowLayout manager again, but this time you explicitly
specify that the components are to be centered and the horizontal and vertical gaps are to be 5 and 10
pixels, respectively.
You declare the button variable to use as a temporary store for the reference to each button while you
set it up. You also define a Dimension object that you use to set a common preferred size for the buttons.
The buttons in this case are JButton components, not custom components, so you must set each of them
up here with a listener and a border. You add a raised bevel border to each button to make them look like
buttons — again using a BorderFactory method.
The listener for each button is an object of the inner class HandleControlButton , and you pass the ap-
propriate button ID to the constructor for reasons that are apparent when you define that class. To set the
preferred size for each button object, you call its setPreferredSize() method. The argument is a Di-
mension object that specifies the width and height. Finally, after adding the two buttons to controlPane ,
you add that to the content pane for the applet.
The inner class HandleControlButton defines the listener object for each control button, so let's imple-
ment that next.
TRY IT OUT: Defining the Control Button Handler Class
You have already determined that the HandleControlButton class constructor accepts an argument that
identifies the particular button for which it is listening. This is to enable the actionPerformed() meth-
od in the listener class to choose the course of action appropriate to the button that originated the event.
Here's the inner class definition to do that:
Search WWH ::




Custom Search