Java Reference
In-Depth Information
int fontStyle = font.getStyle();
if(e.getStateChange()==ItemEvent.SELECTED) { // If style was selected
fontStyle |= style;
// turn it on in the font style
} else {
fontStyle &= ~style;
// otherwise turn it off
}
font = font.deriveFont(fontStyle);
// Get a new font
fontDisplay.setFont(font);
// Change the label font
fontDisplay.repaint();
// repaint
}
private int style;
// Style for this listener
}
Directory "Sketcher 5 displaying a font dialog"
The constructor accepts an argument that is the style for the button, so the value of the member, style ,
is the value you want to set in the fontStyle member that you use to create a new Font object, either
Font.BOLD or Font.ITALIC . You initialize the fontStyle variable with the current font style. Because the
listener for a particular button already contains the corresponding style, the itemStateChanged() method
that is called when an item event occurs just switches the value of style in fontStyle either on or off,
depending on whether the radio button was selected or deselected. It then derives a font with the new style,
sets it in the fontDisplay label, and repaints the label.
You have now completed the FontDialog class. If you have been creating the code yourself, now would
be a good time to try compiling the class to see what is missing — import statements, usually. All you need
now is some code in the SketcherFrame class to make use of it.
TRY IT OUT: Using the Font Dialog
To get the font dialog operational in Sketcher, you can add an Options menu to the menu bar with a
Choose font . . . menu item, and install a listener for the menu item. First, add SketcherFrame members
to store the JMenu object for the Options menu and an instance of the font dialog:
private JMenu optionsMenu;
// Options menu
private FontDialog fontDlg;
// The font
dialog
You can also add a member to store the menu item in the Options menu:
private JMenuItem fontItem;
// Font chooser
menu item
Now you can create the Options menu with the following code in the SketcherFrame constructor:
public SketcherFrame(String title, Sketcher theApp) {
setTitle(title); // Set the
window title
this.theApp = theApp; // Save
Search WWH ::




Custom Search