Java Reference
In-Depth Information
Try It Out - Using the Font Dialog
To get the font dialog operational in Sketcher, we need to add a new menu, Options , to the menu bar
with a Choose font... menu item, and we need to install a listener for it. To keeps things ship-shape it
would be best to add the fragments of code in the SketchFrame constructor in the places where we do
similar things.
Create the Options menu with the following constructor code:
JMenu fileMenu = new JMenu("File"); // Create File menu
JMenu elementMenu = new JMenu("Elements"); // Create Elements menu
JMenu optionsMenu = new JMenu("Options"); // Create options menu
JMenu helpMenu = new JMenu("Help"); // Create Help menu
fileMenu.setMnemonic('F'); // Create shortcut
elementMenu.setMnemonic('E'); // Create shortcut
optionsMenu.setMnemonic('O'); // Create shortcut
helpMenu.setMnemonic('H'); // Create shortcut
You can add the menu item like this, somewhere in the constructor:
// Add the font choice item to the options menu
fontItem = new JMenuItem("Choose font...");
fontItem.addActionListener(this);
optionsMenu.add(fontItem);
We can add a declaration for the fontItem member of the SketchFrame class by adding it to the
existing declaration for the aboutItem , which is probably somewhere near the bottom in your file. It
may take some hunting with the amount of code we have got in this class now:
private JMenuItem aboutItem, fontItem;
You need to add the Options menu to the menu bar before the Help menu to be consistent with convention:
menuBar.add(fileMenu); // Add the file menu
menuBar.add(elementMenu); // Add the element menu
menuBar.add(optionsMenu); // Add the options menu
You can create a FontDialog object by adding a statement to the end of the SketchFrame constructor:
fontDlg = new FontDialog(this);
We can reuse the FontDialog object as often as we want. All we need to do to display it is to call its
setVisible() method. Of course, we will need to declare fontDlg as a member of the
SketchFrame class:
private FontDialog fontDlg; // The font dialog
Search WWH ::




Custom Search