01: package com.vividsolutions.jump.workbench.ui;
02:
03: import java.awt.BorderLayout;
04: import java.awt.Component;
05: import java.awt.Dialog;
06: import java.awt.Frame;
07: import java.awt.HeadlessException;
08: import java.awt.event.ActionEvent;
09: import java.awt.event.ActionListener;
10: import javax.swing.JDialog;
11: import javax.swing.JOptionPane;
12: import java.awt.event.WindowAdapter;
13: import java.awt.event.WindowEvent;
14:
15: /**
16: * Hosts a custom component in a dialog with OK and Cancel buttons. Also
17: * validates the input if OK is pressed.
18: */
19: public class OKCancelDialog extends JDialog {
20:
21: /**
22: *
23: * @param owner
24: * @param title
25: * @param modal
26: * @param customComponent
27: * @param validator the {@link Validator} to use, or <code>null</code> if none required
28: * @throws HeadlessException
29: */
30: public OKCancelDialog(Dialog owner, String title, boolean modal,
31: Component customComponent, Validator validator)
32: throws HeadlessException {
33: super (owner, title, modal);
34: initialize(customComponent, validator);
35: }
36:
37: public OKCancelDialog(Frame owner, String title, boolean modal,
38: Component customComponent, Validator validator)
39: throws HeadlessException {
40: super (owner, title, modal);
41: initialize(customComponent, validator);
42: }
43:
44: private OKCancelPanel okCancelPanel = new OKCancelPanel();
45: private Component customComponent;
46:
47: private void initialize(final Component customComponent,
48: final Validator validator) {
49: getRootPane().setDefaultButton(okCancelPanel.getButton("OK"));
50: this .customComponent = customComponent;
51: getContentPane().setLayout(new BorderLayout());
52: getContentPane().add(customComponent, BorderLayout.CENTER);
53: okCancelPanel.addActionListener(new ActionListener() {
54: public void actionPerformed(ActionEvent e) {
55: if (okCancelPanel.wasOKPressed() && validator != null) {
56: String errorMessage = validator
57: .validateInput(customComponent);
58: if (errorMessage != null) {
59: JOptionPane.showMessageDialog(
60: OKCancelDialog.this , errorMessage,
61: getTitle(), JOptionPane.ERROR_MESSAGE);
62: return;
63: }
64: }
65: setVisible(false);
66: }
67: });
68:
69: addWindowListener(new WindowAdapter() {
70: public void windowClosing(WindowEvent e) {
71: okCancelPanel.setOKPressed(false);
72: }
73: });
74:
75: getContentPane().add(okCancelPanel, BorderLayout.SOUTH);
76: pack();
77: // Don't centre dialog until its size has been determined
78: // i.e. after calling #pack [Jon Aquino 2005-03-09]
79: GUIUtil.centreOnWindow(this );
80: }
81:
82: public static interface Validator {
83: /**
84: * @return an error message, or null if the input is valid
85: */
86: public String validateInput(Component component);
87: }
88:
89: public boolean wasOKPressed() {
90: return okCancelPanel.wasOKPressed();
91: }
92:
93: public Component getCustomComponent() {
94: return customComponent;
95: }
96: }
|