Java Reference
In-Depth Information
// Set up font list choice component as before...
// Panel to display font sample as before...
// Create a split pane with font choice at the top as before...
// Set up the size choice using a spinner
JPanel sizePane = new JPanel(); // Pane for size choices
label = new JLabel("Choose point size"); // Prompt for point size
sizePane.add(label); // Add the prompt
chooseSize = new JSpinner(new SpinnerNumberModel(fontSize,
pointSizeMin, pointSizeMax, pointSizeStep));
chooseSize.addChangeListener(this); sizePane.add(chooseSize);
// Add spinner to pane
gbLayout.setConstraints(sizePane, constraints); // Set pane constraints
dataPane.add(sizePane); // Add the pane
// Plus the code for the rest of the constructor...
}
We again create a panel to contain the spinner and its associated prompt as it makes the layout easier. The
default
FlowLayout
in the panel is fine for what we want. We had better add a couple more members to the
FontDialog
class to store the references to the
chooseSize
and
fontDisplay
objects:
private JSpinner chooseSize; // Font size options
private JLabel fontDisplay; // Font sample
A spinner generates
ChangeEvent
events when an item is selected that are sent to listeners of type
ChangeListener
. The listener for our spinner is the
FontDialog
object so we need to specify that it
implements the
ChangeListener
interface:
class FontDialog extends JDialog
implements Constants, ListSelectionListener,
ActionListener, ChangeListener {
The
ChangeListener
interface defines one method,
stateChanged()
, which has a parameter of type
ChangeEvent
. You obtain a reference to the source of the event by calling
getSource()
for the event
object. You then need to cast the reference to the type of the source, in our case,
JSpinner
. For example:
public void stateChanged(ChangeEvent e) {
JSpinner source = (JSpinner)e.getSource();
}
Of course, we want the value that is now selected in the spinner and the
getValue()
method will
return a reference to this as type
Object
. Since we are using a
SpinnerNumberModel
object as the
spinner model, the object encapsulating the value will actually be of type
Number
so we will have to
cast the reference returned by
getValue()
to this type. We can get a little closer to want we what by
amending our
stateChanged()
method to: