Java Reference
In-Depth Information
// Set up the size choice using a spinner as before...
// Set up style options using radio buttons
bold = new JRadioButton("Bold", (font.getStyle() & Font.BOLD) > 0);
italic = new JRadioButton("Italic", (font.getStyle() & Font.ITALIC) > 0);
bold.addItemListener(new StyleListener(Font.BOLD)); // Add button listeners
italic.addItemListener(new StyleListener(Font.ITALIC));
JPanel stylePane = new JPanel(true);
// Create style pane
stylePane.add(bold);
// Add buttons
stylePane.add(italic);
// to style pane...
gbLayout.setConstraints(stylePane, constraints);
// Set pane constraints
dataPane.add(stylePane);
// Add the pane
getContentPane().add(dataPane, BorderLayout.CENTER);
pack();
setVisible(false);
}
Directory "Sketcher 5 displaying a font dialog"
It looks like a lot of code, but it's repetitive, as you have two radio buttons. The second argument to the
JRadioButton
constructor sets the state of the button. If the existing style of the current font is
BOLD
and/
or
ITALIC
, the initial states of the buttons are set accordingly. You add a listener of type
StyleListener
for each button, and you add a definition for
StyleListener
as an inner class to
FontDialog
in a moment.
Note that you pass the style constant that corresponds to the set state of the button to the constructor for the
listener.
The
stylePane
object presents the buttons using the default
FlowLayout
manager, and this pane is added
as the last row to
dataPane
. The final step is to add the
dataPane
object as the central pane in the content
pane for the dialog. The call to
pack()
lays out the dialog components with their preferred sizes if possible,
and the
setVisible()
call with the argument
false
means that the dialog is initially hidden. Because this is
a complex dialog, you don't want to create a new object each time you want to display the font dialog. You
just call the
setVisible()
method for the dialog object with the argument
true
when you want to display
it.
Listening for Radio Buttons
The inner class,
StyleListener
, in the
FontDialog
class works on principles that you have seen before.
A radio button (or a checkbox) generates events of type
java.awt.ItemEvent
, and the listener class must
implement the
java.awt.ItemListener
interface:
class StyleListener implements ItemListener {
public StyleListener(int style) {
this.style = style;
}
public void itemStateChanged(ItemEvent e) {