Java Reference
In-Depth Information
}
Directory "Sketcher 5 displaying a font dialog"
Add a static
import
statement for the constants in the
SketcherConstants
class:
import static Constants.SketcherConstants.*;
You again create a panel to contain the spinner and its associated prompt to make the layout easier. The
default
FlowLayout
in the panel is fine for what you want. You 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 an event of type
ChangeEvent
when an item is selected that is sent to listeners of type
ChangeListener
. Both types are defined in the
javax.swing.event
package. The listener for our spinner
is the
FontDialog
object, so you need to specify that it implements the
ChangeListener
interface:
class FontDialog extends JDialog
implements ActionListener, // For buttons etc.
ListSelectionListener,
// For list box
ChangeListener {
// For the spinner
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 this case,
JSpinner
. For example, you
could code it like this:
public void stateChanged(ChangeEvent e) {
JSpinner source = (JSpinner)e.getSource();
// ...plus code to deal with the spinner event for source...
}
Directory "Sketcher 5 displaying a font dialog"
Of course, you want the value that is now selected in the spinner, and the
getValue()
method returns a
reference to this as type
Object
. Because you are using a
SpinnerNumberModel
object as the spinner mod-
el, the object encapsulating the value is actually of type
Number
, so you can cast the reference returned by
getValue()
to this type. You can get a little closer to what you want by amending our
stateChanged()
method to: