Implementation notes for the initialization dialog box
In a typical implementation, the action listener attached to the `ok' button
takes care of copying the values from the various text fields to the appropriate
internal variables. For example, the contents of the `tiles per street
segment' field might be converted into an int and then stored
in the [non-final] public static variable StreetSegment.tilesPerSegment.
(Caveat: many people would prefer that a "setter" method be used
instead of directly accessing the variable.) In the reverse direction,
the constructor usually takes care of copying values from the internal
variables into the corresponding text fields...
class InitializationDialog extends JDialog {
// ...
protected JTextField tilesPerSegmentField;
// ...
public InitializationDialog(Frame owner) {
// ...
tilesPerSegmentField = new JTextField(4); // ...four characters wide
JButton okButton = new JButton("OK");
okButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e)
{ acceptChanges(); setVisible(false); }
});
// ...
initializeFields();
pack(); setVisible(true);
}
protected void initializeFields() {
// copy the "internal" values into the corresponding text fields...
tilesPerSegmentField.setText
(String.valueOf(StreetSegment.tilesPerSegment));
// ...
}
protected void acceptChanges() {
// copy the contents of the text fields into the corresponding
// internal variables...
StreetSegment.tilesPerSegment =
Integer.parseInt(tilesPerSegmentField.getText());
// ...
// [...in real life, we'd do input validation as well...]
}
// ...
}
Those who'd like to see a complete example of this kind of dialog <-->
model interaction might want to take a look at the
sample
solution for last semester's
assignment
2---the file NewGameDialog.java contains the code for their
initialization dialog. (Caveat: they take a slightly different approach
from what's shown above; also, they don't use Swing.)