Hi!
This is my code for JDialog, which adds name and phone number to TableModel. It also chceck phone number format before adding it. The problem is, that both clicking on Cancel button and successful adding should set dialog invisible, but it only works on second attempt ->
1) if I click Cancel, nothing happens, if I click it another time, dialog disappears.
2) if I click Add and phone number is correct, it is added to TableModel (I can see that), but dialog remains, if I click Add again (with new data), again everything is added and dialog disappears
What is wrong here? Thanks!
public class InsertDialog extends JDialog
implements PropertyChangeListener {
private static final long serialVersionUID = 1915361976867368594L;
private DefaultTableModel model;
private JOptionPane optionPane;
private static final String ADD_LABEL = "Add";
private static final String CANCEL_LABEL = "Cancel";
private JTextField textName = new JTextField();
private JTextField textPhoneNr = new JTextField();
/**
* Initializes dialog and sets associated TableModel.
* @param model - TableModel with data
*/
public InsertDialog(DefaultTableModel model) {
this.model = model;
setTitle("Add new name and phone number");
String msg1 = "Enter the name";
String msg2 = "Enter the phone number";
Object[] array = {msg1, textName, msg2, textPhoneNr};
Object[] options = {ADD_LABEL, CANCEL_LABEL};
optionPane = new JOptionPane(array, JOptionPane.PLAIN_MESSAGE,
0, null, options);
setContentPane(optionPane);
optionPane.addPropertyChangeListener(this);
}
/**
* Reacts on mouse clicks on buttons within dialog.
* @param propEvt
*/
public void propertyChange(PropertyChangeEvent propEvt) {
String prop = propEvt.getPropertyName();
if (JOptionPane.VALUE_PROPERTY.equals(prop)
|| JOptionPane.INPUT_VALUE_PROPERTY.equals(prop)) {
Object value = optionPane.getValue();
if (value == JOptionPane.UNINITIALIZED_VALUE) {
return;
}
optionPane.setValue(JOptionPane.UNINITIALIZED_VALUE);
if (ADD_LABEL.equals(value)) {
String phone = phoneNumberCheck();
if (phone != null) {
model.insertRow(textName.getText(), textPhoneNr.getText());
}
}
else {
setVisible(false);
}
}
}
private String phoneNumberCheck() {
Pattern pattern = Pattern.compile("\\+#(\\d{1})\\-(\\d{9})");
Matcher matcher = pattern.matcher(textPhoneNr.getText().trim());
if (!matcher.matches()) {
ErrDialog.phoneNrErr();
return null;
}
else {
setVisible(false);
return textPhoneNr.getText().trim();
}
}
}