Java Reference
In-Depth Information
for(int i = 0 ; i < NUMBER_COUNT ; ++i) {
luckyNumbers[i] = new Selection(choices[i]);
// Button is it's own listener
luckyNumbers[i].addActionListener(luckyNumbers[i]);
buttonPane.add(luckyNumbers[i]);
}
content.add(buttonPane);
// Set up the control buttons...
}
Directory "Lottery 1"
How It Works
The init() method uses the invokeLater() method from the SwingUtilities class to execute the
createGUI() method on the event-dispatching thread. This guarantees that there is no possibility of a
deadlock arising in the GUI construction process. This is the same technique that you used in the previ-
ous example.
The first step in the createGUI() method is to define the layout manager for the applet. To make the
layout easier, you use one panel to hold the selection buttons and another to hold the control buttons. You
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 contains the lucky number buttons and the bottom
panel contains 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 “nat-
ural" or “preferred size," so you set the preferred size for the buttons in the Selection class constructor.
You decorate the panel with a border by calling its setBorder() method. The argument is the reference
that is returned by the static createTitledBorder() method from the BorderFactory class. The first
argument to createTitledBorder() is the border to be used, and the second is the title.
You 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 construct-
ors directly is that border objects are shared where possible, so you can use a particular border in various
places in your code and only one object is created.
The buttons to display the chosen numbers are of type Selection , and you get to the detail of this inner
class in a moment. You call the static getNumbers() method to obtain the first set of random values for
the buttons. You then create and store each button in the luckyNumbers array and add it to the panel in the
for loop. Because these buttons are going to listen for their own events, you call the addActionListen-
er() method for each button with a reference to the button as the argument. The last step here is to add
the buttonPane panel to the content pane for the applet.
You can now add the code for the control buttons to the createGUI() method.
TRY IT OUT: Setting Up the Control Buttons
Search WWH ::




Custom Search