我可以以非模态方式使用Java JOptionPane吗?

时间:2011-04-18 17:17:02

标签: java joptionpane

我正在处理一个应用程序,当某个动作发生时会弹出一个JOptionPane。我只是想知道当JOptionPane确实弹出时你是否仍然可以使用后台应用程序。目前,当JOptionPane弹出时,除非关闭JOptionPane,否则我无法执行任何其他操作。

修改

感谢回复人员和信息。认为生病了将此功能从应用程序中删除,因为看起来它可能比必要的更麻烦。

5 个答案:

答案 0 :(得分:6)

文档通过showXXXDialog方法明确指出all dialogs are modal

您可以使用的是从文档中获取的直接使用方法以及JDialog从Dialog继承的setModal方法:

 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;

答案 1 :(得分:2)

您应该可以在此处获得更多信息:http://download.oracle.com/javase/tutorial/uiswing/components/dialog.html

  

对话框可以是模态的。当一个模态   对话框可见,它会阻止用户   输入到的所有其他窗口   程序。 JOptionPane创建JDialogs   这是模态的。创建非模态   对话框,您必须使用JDialog类   直接

     

从JDK6开始,您可以修改   使用对话窗口模态行为   the new Modality API。见新   Modality API了解详情。

答案 2 :(得分:1)

在你的Java应用程序中,我认为你运气不好:我没有检查过,但我认为JOptionPane的showXXXDialog方法会弹出一个所谓的模态对话框,它将来自同一JVM的其余GUI保持为非活动状态

然而,Java没有任何前瞻性的超能力:你仍然可以使用Alt-Tab到其他(非Java)应用程序。

答案 3 :(得分:1)

这个简单的调整对我有用(1.6+)。用四行代码替换showXXXDialog: (1)创建一个JOptionPane对象 (2)调用其createDialog()方法来获取JDialog对象 (3)将JDialog对象的模态类型设置为无模式 (4)将JDialog的可见性设置为true。

答案 4 :(得分:1)

@justkt的答案的改进版本,在其注释中建议了事件侦听器。

    // A non-modal version of JOptionPane.showOptionDialog()
    JOptionPane pane = new JOptionPane(arguments, ...);
    pane.setComponentOrientation(JOptionPane.getRootFrame().getComponentOrientation());
    JDialog dialog = pane.createDialog((Component)parent, "title");

    pane.addPropertyChangeListener(JOptionPane.VALUE_PROPERTY, ignored -> {
        Object selectedValue = pane.getValue();
        System.out.print("Out of " + Arrays.toString(pane.getOptions()) + ", ");
        System.out.println(selectedValue + " was selected");
        dialog.dispose();
    });

    dialog.setModal(false);
    dialog.setVisible(true);
相关问题