Java Reference
In-Depth Information
JPanel buttonPane = new JPanel(); // Add the pane containing numbers
// Let's have a fancy panel border
buttonPane.setBorder(BorderFactory.createTitledBorder(
BorderFactory.createEtchedBorder(Color.cyan,
Color.blue),
"Every One a Winner!"));
int[] choices = getNumbers(); // Get initial set of numbers
for(int i = 0; i<numberCount; i++) {
luckyNumbers[i] = new Selection(choices[i]);
buttonPane.add(luckyNumbers[i]);
}
content.add(buttonPane);
// Set up the control buttons...
}
How It Works
The first step is to define the layout manager for the applet. To make the layout easier, we will use one
panel to hold the selection buttons and another to hold the control buttons. We can position these
panels one above the other by specifying the layout manager for the content pane of the applet as a grid
layout with one column. The top panel will contain the lucky number buttons and the bottom panel will
contain the control buttons.
The buttonPane panel that holds the lucky number buttons is of type JPanel , so it has a
FlowLayout object as its layout manager by default. A flow layout manager allows components to
assume their 'natural' or 'preferred size', so we will set the preferred size for the buttons in the
Selection class constructor. We decorate the panel with a border by calling its setBorder()
method. The argument is returned by the static createTitledBorder() method from the
BorderFactory class. The first argument passed to createTitledBorder() is the border to be
used, and the second is the title.
We use an etched border that is returned by another static method in the BorderFactory class. The
two arguments to this method are the highlight and shadow colors to be used for the border. A big
advantage of using the BorderFactory methods rather than creating border objects from the border
class constructors directly is that border objects will be shared where possible, so you can use a
particular border in various places in your code and only one object will be created.
The buttons to display the chosen numbers will be of type Selection , and we will get to the detail of
this inner class in a moment. We call our static method getNumbers() to obtain the first set of
random values for the buttons. We then create and store each button in the luckyNumbers array and
add it to the panel in the for loop. Since these buttons are going to listen for their own events, we don't
need to worry about setting separate action listeners for them. The last step here is to add the
buttonPane panel to the content pane for the applet.
We should now add the code for the control buttons to the init() method.
Search WWH ::




Custom Search