How to prevent JOptionPane.showConfirmDialog box from closing

a 夏天 提交于 2019-12-11 08:46:04

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!