Java Reference
In-Depth Information
public void stateChanged(ChangeEvent e) {
Number value = (Number)((JSpinner)e.getSource()).getValue();
}
We are not really interested in a Number object though. What we want is the integer value so we can
store it in the fontSize member of the dialog and then derive a new font. The intValue() method
for the Number object will produce that. We can therefore arrive at the final version of setChanged()
that does what we want:
public void stateChanged(ChangeEvent e) {
fontSize = ((Number)(((JSpinner)e.getSource()).getValue())).intValue();
font = font.deriveFont((float)fontSize);
fontDisplay.setFont(font);
fontDisplay.repaint();
}
That first statement looks quite daunting but since we put it together a step at a time, you should see
that it isn't really difficult - just a lot of parentheses to keep in sync.
Using Radio Buttons to Select the Font Style
We will create two JRadioButton objects for selecting the font style. One will select bold or not, and
the other will select italic or not. A plain font is simply not bold or italic. You could use JCheckBox
objects here if you prefer - they would work just as well. Here's the code:
public FontDialog(SketchFrame window) {
// Initialization as before...
// Button panel code as before...
// Set up the data input panel to hold all input components as before...
// Add the font choice prompt label as before...
// 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 as before...
// Set up style options using radio buttons
JRadioButton bold = new JRadioButton("Bold", (fontStyle & Font.BOLD) > 0);
JRadioButton italic = new JRadioButton("Italic", (fontStyle & Font.ITALIC) > 0);
bold.addItemListener(new StyleListener(Font.BOLD)); // Add button listeners
italic.addItemListener(new StyleListener(Font.ITALIC));
JPanel stylePane = new JPanel(); // 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);
}
Search WWH ::




Custom Search