Can I use a Java JOptionPane in a non-modal way?

yemyem picture yemyem · Apr 18, 2011 · Viewed 15.7k times · Source

I am working on an application which pops up a JOptionPane when a certain action happens. I was just wondering if it was possible that when the JOptionPane does pop up how can you still use the background applications. Currently when the JOptionPane pops up I can't do anything else until I close the JOptionPane.

EDIT

Thanks for the reply guys and the information. Think ill leave this function out of the application cause it looks like it could be more hassle than necessary.

Answer

justkt picture justkt · Apr 18, 2011

The documentation explicitly states that all dialogs are modal when created through the showXXXDialog methods.

What you can use is the Direct Use method taken from the docs and the setModal method that JDialog inherits from Dialog:

 JOptionPane pane = new JOptionPane(arguments);
 // Configure via set methods
 JDialog dialog = pane.createDialog(parentComponent, title);
 // the line below is added to the example from the docs
 dialog.setModal(false); // this says not to block background components
 dialog.show();
 Object selectedValue = pane.getValue();
 if(selectedValue == null)
   return CLOSED_OPTION;
 //If there is not an array of option buttons:
 if(options == null) {
   if(selectedValue instanceof Integer)
      return ((Integer)selectedValue).intValue();
   return CLOSED_OPTION;
 }
 //If there is an array of option buttons:
 for(int counter = 0, maxCounter = options.length;
    counter < maxCounter; counter++) {
    if(options[counter].equals(selectedValue))
    return counter;
 }
 return CLOSED_OPTION;