问题
I'm showing a ConfirmDialog with some input fields. When save fails (validation fails) I want to show a MessageDialog box but I don't want the ConfirmDialog box to disappear. How do I do this?
Below is my actionPerformed method to open the ConfirmDialog (when I click a button with this method as it's event handler)
@Override
public void actionPerformed(ActionEvent e) {
int result = JOptionPane.showConfirmDialog(null, panel, "New transaction",
JOptionPane.OK_CANCEL_OPTION, JOptionPane.PLAIN_MESSAGE);
if (result == JOptionPane.OK_OPTION) {
// save transaction
Transaction transaction = new Transaction();
// ...
if (transaction.save()) {
// close the ConfirmDialog is OK, save was successful
} else {
// don't close the ConfirmDialog, save failed
JOptionPane.showMessageDialog(panel, "Please fix the errors");
}
}
}
回答1:
You can't use the static methods of the JOptionPane class to create the dialog.
You need to create your own dialog and then use the JOptionPane as the contentPane of your dialog.
Read the section from the Swing tutorial on Stopping Automatic Dialog Closing for example code on how this can be done.
来源:https://stackoverflow.com/questions/39627656/how-to-prevent-joptionpane-showconfirmdialog-box-from-closing