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

三世轮回 提交于 2019-11-26 11:27:17

问题


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.


回答1:


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;



回答2:


You should be able to get more information here: http://download.oracle.com/javase/tutorial/uiswing/components/dialog.html

A Dialog can be modal. When a modal Dialog is visible, it blocks user input to all other windows in the program. JOptionPane creates JDialogs that are modal. To create a non-modal Dialog, you must use the JDialog class directly.

Starting with JDK6, you can modify Dialog window modality behavior using the new Modality API. See The New Modality API for details.




回答3:


Within your Java application, I think you're out of luck: I haven't checked, but I think that JOptionPane's showXXXDialog methods pop up a so-called modal dialog that keeps the rest of the GUI from the same JVM inactive.

However, Java doesn't have any foreground-grabbing super powers: You should still be able to Alt-Tab to other (non-Java) applications.




回答4:


This easy tweak worked for me (1.6+). Replaced the showXXXDialog with four lines of code to: (1) create a JOptionPane object (2) call its createDialog() method to get a JDialog object (3) set the modality type of the JDialog object to modeless (4) set the visibility of the JDialog to true.



来源:https://stackoverflow.com/questions/5706455/can-i-use-a-java-joptionpane-in-a-non-modal-way

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