Java Reference
In-Depth Information
You set the preferred size of the button here to ensure that the buttons are all of the same size. Without
this call, each button would be sized to fit its label, so the dialog would look a bit untidy. The listener is the
FontDialog
class object, so the
FontDialog
class must implement the
ActionListener
interface, which
implies that an
actionPerformed(
) method must be defined in the class:
import java.awt.*;
import javax.swing.*;
import java.awt.event.*;
class FontDialog extends JDialog implements ActionListener {
// Constructor definition...
// createButton() definition...
public void actionPerformed(ActionEvent e) {
if(e.getSource()== ok) {
// If it's the OK button
((SketcherFrame)getOwner()).setFont(font);
// ...set selected font
} else {
font = ((SketcherFrame)getOwner()).getFont();
// Restore the current font
fontDisplay.setFont(font);
chooseSize.setValue(font.getSize());
// Restore the point size
fontList.setSelectedValue(font.getName(),true);
int style = font.getStyle();
bold.setSelected((style & Font.BOLD) > 0); // Restore the
italic.setSelected((style & Font.ITALIC) > 0); // style options
}
// Now hide the dialog - for ok or cancel
setVisible(false);
}
// Plus the rest of the class definition...
}
Directory "Sketcher 5 displaying a font dialog"
The
getSource()
member of the
ActionEvent
object
e
returns a reference to the object that originated
the event, so you can use this to determine the button that originated the event. You just compare the
source
object reference with the OK button reference to determine whether it was clicked. If it is the OK button,
you call the
setCurrentFont()
method in the
SketcherFrame
object that is the parent for this dialog to set
the font. You then just hide the dialog so Sketcher can continue. When the Cancel button is selected for the
dialog, you must restore the dialog to the state it was in when it opened. The user may have changed some
of the selections before clicking Cancel, so you set things back so they correspond to the font stored in the
SketcherFrame
object. The
getOwner()
method for the dialog returns a reference to the parent window.
Of course, you must add the definition of
setFont()
to the
SketcherFrame
class:
// Method to set the current font
public void setFont(Font font) {