Java Reference
In-Depth Information
How It Works
We create another JPanel object to hold the control buttons and just to show that we can, we pass a
layout manager object to the constructor. It's a FlowLayout manager again, but this time we explicitly
specify that the components are to be centered and the horizontal and vertical gaps are to be 5 and 10
pixels respectively.
We declare the button variable to use as a temporary store for the reference to each button while we
set it up. We also define a Dimension object that we will use to set a common preferred size for the
buttons. The buttons are JButton components, not custom components, so we must set each of them
up here with a listener and a border. We 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 we pass the
appropriate button ID to the constructor for reasons that will be apparent when we define that class. To
set the preferred size for each button object, we call its setPreferredSize() method. The argument
is a Dimension object that specifies the width and height. Finally, after adding the two buttons to
controlPane , we add that to the content pane for the applet.
The inner class HandleControlButton defines the listener object for each control button, so let's
implement that next.
Try It Out - Defining the Control Button Handler Class
We have already determined that the class constructor will accept an argument that identifies the particular
button for which it is listening. This is to enable the actionPerformed() method in the listener class to
choose the course of action appropriate to the button. Here's the inner class definition to do that:
class HandleControlButton implements ActionListener {
private int buttonID;
// Constructor
public HandleControlButton(int buttonID) {
this.buttonID = buttonID; // Store the button ID
}
// Handle button click
public void actionPerformed(ActionEvent e) {
switch(buttonID) {
case PICK _ LUCKY _ NUMBERS:
int[] numbers = getNumbers(); // Get maxCount random numbers
for(int i = 0; i < numberCount; i++)
luckyNumbers[i].setValue(numbers[i]); // Set the button values
break;
case COLOR:
Color color = new Color(
flipColor.getRGB()^luckyNumbers[0].getBackground().getRGB());
for(int i = 0; i < numberCount; i++)
luckyNumbers[i].setBackground(color); // Set the button colors
break;
Search WWH ::




Custom Search