Search code examples
javaswingjdialogstoring-data

how to store JDialog in JDialog object created by JOptionPane


I create JDialog JOptionPane like

JOptionPane. showMessageDialog(null, "Last Warning!","Warning", JOptionPane.WARNING_MESSAGE);

this shows a Dialog imdietly and return void so I cant store it in JDialog varible.

I want to do something like this

JDialog warning = JOptionPane. showMessageDialog(null, "Last Warning!","Warning", JOptionPane.WARNING_MESSAGE);
// some code
warning.setVisible(true);

How can I do this ?


Solution

  • JOptionPane has both static utility methods for convenience, and allows instance creation for custom operation, like you want. The way to do it is more verbose, but is more flexible:

    JOptionPane pane = new JOptionPane("Last Warning!", JOptionPane.WARNING_MESSAGE, JOptionPane.DEFAULT_OPTION);
    JDialog warning = pane.createDialog("Warning");
    
    // more code...
    
    warning.setVisible(true);
    

    For more info, I suggest looking at the source code for JOptionPane.showOptionDialog(...), as it shows how to configure the dialog for various messages types, initial value, etc. Alernatively, have a look at How to Make Dialogs from the Java Tutorials.