Java Reference
In-Depth Information
The buttonPane object will have a FlowLayout manager by default, so this will take care of
positioning the buttons. We add the button pane to the dialog content pane using
BorderLayout.SOUTH to place it at the bottom of the window. Because creating each button involves
several steps, we are using a helper method createButton() that only requires the button label as an
argument. Note that we store each button reference in a variable, so we will need to add these as
members of the FontDialog class:
private JButton ok; // OK button
private JButton cancel; // Cancel button
We will use these references in the listeners for the button, as we will see in a moment.
We can code the createButton() method as a member of the FontDialog class as follows:
JButton createButton(String label) {
JButton button = new JButton(label); // Create the button
button.setPreferredSize(new Dimension(80,20)); // Set the size
button.addActionListener(this); // Listener is the dialog
return button; // Return the button
}
We set the preferred size of the button here to ensure the buttons are all the same size. Without this call,
each button would be sized to fit its label so it would look a bit untidy. The listener is the FontDialog
class, so the FontDialog must implement the ActionListener interface, which implies an
actionPerformed() method:
class FontDialog extends JDialog
implements Constants, ActionListener { // For buttons etc.
// Constructor definition...
// createButton() definition...
public void actionPerformed(ActionEvent e) {
Object source = e.getSource(); // Get the source of the event
if(source == ok) { // Is it the OK button?
((SketchFrame)getOwner()).setCurrentFont(font); // Set the selected font
setVisible(false); // Hide the dialog
}
else if(source == cancel) // If it is the Cancel button
setVisible(false); // just hide the dialog
}
// Plus the rest of the class definition...
}
The getSource() member of the ActionEvent object, e , returns a reference to the object that
originated the event, so we can use this to determine which button the method is being called for. We
just compare the source object (which is holding the reference to the object to which the event applies)
to each button object in turn. If it is the OK button, we call the setCurrentFont() method in the
SketchFrame object that is the parent for this dialog to set the font. If it is the Cancel button we just
hide the dialog so Sketcher can continue. Of course we must add the definition of setCurrentFont()
to the SketchFrame class. The code for this will be:
Search WWH ::




Custom Search