public class BaseDialog extends JDialog {
protected BaseDialog(Frame owner, String title) {
super(owner, title, true);
}
protected boolean dataIsValid() { return true; }
protected void setModelFromView() {}
protected JButton stdOKButton() {
JButton button = new JButton("OK");
button.setMnemonic('O');
getRootPane().setDefaultButton(button);
button.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
if (dataIsValid()) {
setModelFromView();
setVisible(false);
}
}
});
return button;
}
protected JButton stdCancelButton() {
JButton button = new JButton("Cancel");
button.setMnemonic('C');
button.setDefaultCapable(false);
button.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
setVisible(false);
}
});
return button;
}
|
This dialog practically manages itself...
private void doExampleDialog() {
JDialog dialog = new ExampleDialog(frame, data);
dialog.setVisible(true);
}
|
|
public class ExampleDialog extends BaseDialog {
private SomeClass data;
private JTextField nameText;
private JTextField phoneText;
public ExampleDialog(Frame owner, SomeClass data) {
super(owner, "Exemplary Dialog");
this.data = data;
createComponents();
setViewFromModel();
layoutComponents();
setLocationRelativeTo(owner);
}
// data validation -- note chaining of methods
protected boolean dataIsValid() {
return nameIsOK() && phoneIsOK();
}
// this only gets called if the user clicks OK
protected void setModelFromView() {
data.setName(nameText.getText());
data.setPhone(phoneText.getText());
}
// use a method like this to init your components
private void setViewFromModel() {
nameText.setText(data.getName());
phoneText.setText(data.getPhone());
}
private boolean nameIsOK() {
if (nameText.getText().length() > 0) {
return true;
}
showErrorMsg("You must enter a name.");
nameText.requestFocus();
return false;
}
private boolean phoneIsOK() {
if (phoneText.getText().length() > 0) {
return true;
}
showErrorMsg("You must enter a phone number.");
phoneText.requestFocus();
return false;
}
|
|