001package edu.pdx.cs410J.family;
002
003import java.awt.*;
004import java.awt.event.*;
005import java.io.*;
006import java.text.*;
007import java.util.*;
008
009import javax.swing.*;
010import javax.swing.border.*;
011
012/**
013 * This is a dialog for creating a new <code>Person</code>.
014 */
015@SuppressWarnings("serial")
016public class AddPersonDialog extends JDialog {
017
018  // The person we're creating
019  private Person newPerson = null;
020
021  private Person mother;
022  private Person father;
023
024  /**
025   * Creates a new <code>AddPersonDialog</code> with a given owner
026   * <code>JFrame</code> and <code>FamilyTree</code>.
027   */
028  public AddPersonDialog(JFrame owner, FamilyTree tree) {
029    super(owner, "Add New Person", true /* modal */);
030
031    Container pane = this.getContentPane();
032    pane.setLayout(new BorderLayout());
033
034    JPanel infoPanel = new JPanel();
035    infoPanel.setLayout(new GridLayout(0, 2));
036    Border infoBorder = BorderFactory.createEmptyBorder(5, 5, 5, 5); 
037    infoPanel.setBorder(infoBorder);
038
039    infoPanel.add(new JLabel("id:"));
040    final JTextField idField = new JTextField();
041    infoPanel.add(idField);
042
043    final ButtonGroup group = new ButtonGroup();
044
045    final JRadioButton male = new JRadioButton("male", true);
046    group.add(male);
047    infoPanel.add(male);
048    
049    final JRadioButton female = new JRadioButton("female");
050    group.add(female);
051    infoPanel.add(female);
052
053    infoPanel.add(new JLabel("First name:"));
054    final JTextField firstNameField = new JTextField();
055    infoPanel.add(firstNameField);
056
057    infoPanel.add(new JLabel("Middle name:"));
058    final JTextField middleNameField = new JTextField();
059    infoPanel.add(middleNameField);
060
061    infoPanel.add(new JLabel("Last name:"));
062    final JTextField lastNameField = new JTextField();
063    infoPanel.add(lastNameField);
064
065    infoPanel.add(new JLabel("Date of Birth:"));
066    final JTextField dobField = new JTextField();
067    infoPanel.add(dobField);
068
069    infoPanel.add(new JLabel("Date of Death:"));
070    final JTextField dodField = new JTextField();
071    infoPanel.add(dodField);
072
073    infoPanel.add(new JLabel("Father:"));
074    JPanel fatherPanel = new JPanel();
075    fatherPanel.setLayout(new FlowLayout());
076    final JTextField fatherText = new JTextField("Click to choose");
077    fatherText.setEditable(false);
078    fatherText.addMouseListener(new MouseAdapter() {
079        public void mouseClicked(MouseEvent e) {
080          // Pop up a PersonChooseDialog, place name in TextField
081          System.out.println("Clicked father");
082        }
083      });
084    fatherPanel.add(fatherText);
085    infoPanel.add(fatherPanel);
086
087    infoPanel.add(new JLabel("Mother:"));
088    JPanel motherPanel = new JPanel();
089    motherPanel.setLayout(new FlowLayout());
090    final JTextField motherText = new JTextField("Click to choose");
091    motherText.setEditable(false);
092    motherText.addMouseListener(new MouseAdapter() {
093        public void mouseClicked(MouseEvent e) {
094          // Pop up a PersonChooseDialog, place name in TextField
095          System.out.println("Clicked mother");
096        }
097      });
098    motherPanel.add(motherText);
099    infoPanel.add(motherPanel);
100
101    pane.add(infoPanel, BorderLayout.NORTH);
102
103    // "Add" and "Cancel" buttons
104    JPanel buttonPanel = new JPanel();
105    buttonPanel.setLayout(new BoxLayout(buttonPanel,
106                                        BoxLayout.X_AXIS));
107    buttonPanel.add(Box.createHorizontalGlue());
108
109    JButton addButton = new JButton("Add");
110    addButton.addActionListener(new ActionListener() {
111        public void actionPerformed(ActionEvent e) {
112          // Create a new person based on the information entered in
113          // this dialog
114          int id = 0;
115          try {
116            id = Integer.parseInt(idField.getText());
117
118          } catch (NumberFormatException ex) {
119            error("Invalid id: " + idField.getText());
120            return;
121          }
122
123          String text = null;
124
125          text = dobField.getText();
126          Date dob = null;
127          if (text != null && !text.equals("")) {
128            dob = parseDate(dobField.getText());
129            if (dob == null) {
130              // Parse error
131              return;
132            }
133          }
134
135          text = dodField.getText();
136          Date dod = null;
137          if (text != null && !text.equals("")) {
138            dod = parseDate(dodField.getText());
139            if (dod == null) {
140              // Parse error
141              return;
142            }
143          }
144
145          Person.Gender gender;
146          if (group.getSelection().equals(male)) {
147            gender = Person.MALE;
148
149          } else {
150            gender = Person.FEMALE;
151          }
152          
153          // Okay, everything parsed alright
154          newPerson = new Person(id, gender);
155          newPerson.setFirstName(firstNameField.getText());
156          newPerson.setMiddleName(middleNameField.getText());
157          newPerson.setLastName(lastNameField.getText());
158          newPerson.setDateOfBirth(dob);
159          newPerson.setDateOfDeath(dod);
160
161          if (mother != null) {
162            newPerson.setMother(mother);
163          }
164
165          if (father != null) {
166            newPerson.setFather(father);
167          }
168
169          // We're all happy
170          AddPersonDialog.this.dispose();
171        }
172      });
173    buttonPanel.add(addButton);
174
175    buttonPanel.add(Box.createHorizontalGlue());
176
177    JButton cancelButton = new JButton("Cancel");
178    cancelButton.addActionListener(new ActionListener() {
179        public void actionPerformed(ActionEvent e) {
180          // Read my lips, no new Person!
181
182          AddPersonDialog.this.newPerson = null;
183
184          AddPersonDialog.this.dispose();
185        }
186      });
187    buttonPanel.add(cancelButton);
188
189    buttonPanel.add(Box.createHorizontalGlue());
190
191    pane.add(buttonPanel, BorderLayout.SOUTH);
192  }
193
194  /**
195   * Returns the <code>Person</code> created by this
196   * <code>AddPersonDialog</code>.
197   */
198  public Person getPerson() {
199    return this.newPerson;
200  }
201
202  /**
203   * Tries very, very hard to parse the a date.  We assume that the
204   * text is neither empty nor <code>null</code>.
205   */
206  private Date parseDate(String text) {
207    DateFormat formats[] = new DateFormat[] {
208      DateFormat.getDateInstance(DateFormat.SHORT),
209      DateFormat.getDateInstance(DateFormat.MEDIUM),
210      DateFormat.getDateInstance(DateFormat.LONG),
211      DateFormat.getDateInstance(DateFormat.FULL),
212    };
213
214    for (int i = 0; i < formats.length; i++) {
215      DateFormat df = formats[i];
216      try {
217        Date date = df.parse(text);
218        return date;
219
220      } catch (ParseException ex) {
221        continue;
222      }
223    }
224
225    error("Could not parse date: " + text);
226    return null;
227  }
228
229  /**
230   * Pops up a dialog box with an error message in it.
231   */
232  private void error(String message) {
233    JOptionPane.showMessageDialog(this, new String[] { message}, 
234                                  "Error.",
235                                  JOptionPane.ERROR_MESSAGE);
236  }
237
238  /**
239   * Simple test program.
240   */
241  public static void main(String[] args) {
242    final JFrame frame = new JFrame("Testing AddPersonDialog");
243    JButton button = new JButton("Click me");
244    button.addActionListener(new ActionListener() {
245        public void actionPerformed(ActionEvent e) {
246          FamilyTree tree = new FamilyTree();
247          AddPersonDialog dialog = 
248            new AddPersonDialog(frame, tree);
249          dialog.pack();
250          dialog.setLocationRelativeTo(frame);
251          dialog.setVisible(true);
252
253          Person newPerson = dialog.getPerson();
254          if (newPerson != null) {
255            tree.addPerson(newPerson);
256            PrettyPrinter pretty = 
257              new PrettyPrinter(new PrintWriter(System.out, true));
258            pretty.dump(tree);
259          }
260        }
261      });
262    frame.getContentPane().add(button);
263
264    frame.addWindowListener(new WindowAdapter() {
265        public void windowClosing(WindowEvent e) {
266          System.exit(1);
267        }
268      });
269    frame.pack();
270    frame.setVisible(true);
271  }
272}