当我在两个窗口之间切换时,JDialog消失

时间:2015-03-30 16:14:43

标签: java swing applet awt

我正在尝试创建一个简单的JDialog,它要求用户以3个文本字段的形式输入,并且它正确显示并且其PropertyListener工作得非常好,我还没有为其中的JDialog分配父级构造函数,所以我猜测默认情况下,父设置为我的applet中所有组件的祖先。但是,当我从applet更改为firefox窗口时,当我点击我的applet时,JDialog已经消失了。我是否需要为JDialog设置某个属性以确保它在我切换窗口时保持不变。 starnge的事情是我认为对话框仍然是向上的,但是不可见,因为当第一个对话框出现后,当第一个对话框消失时,两个对话框一次出现(第一个对话框重新出现)。我的JDialog代码如下:

private void addQuestion() {
        questionTextField = new TextField(50);

        Object[] componentsArray = {"Question:", questionTextField, "MQLYes:", mqlYesTextField, "MQLNo:", mqlNoTextField};
        Object[] options = {"Enter", "Cancel"};
        addQuestionDialog = new JDialog(new JFrame(),"Add question");
        addQuestionPane = new JOptionPane(componentsArray, JOptionPane.QUESTION_MESSAGE, JOptionPane.YES_NO_OPTION, null, options, options[0]);

        int x = getX() + getWidth()/2, y = getY() + getHeight()/2;

        addQuestionDialog.setContentPane(addQuestionPane);
        addQuestionDialog.setResizable(false);
        addQuestionDialog.setSize(300,210);
        addQuestionDialog.setVisible(true);
        addQuestionDialog.setLocation(x, y);
        addQuestionDialog.setDefaultCloseOperation(JDialog.HIDE_ON_CLOSE);

        addQuestionPane.addPropertyChangeListener(this);
    }

public void propertyChange(PropertyChangeEvent e) {
    String prop = e.getPropertyName();

    if (addQuestionDialog.isVisible() && (e.getSource() == addQuestionPane) && (JOptionPane.VALUE_PROPERTY.equals(prop) || JOptionPane.INPUT_VALUE_PROPERTY.equals(prop))) {
        Object value = addQuestionPane.getValue();

        if (value == JOptionPane.UNINITIALIZED_VALUE) {
            //ignore reset
            return;
        }

        //Reset the JOptionPane's value.
        //If you don't do this, then if the user
        //presses the same button next time, no
        //property change event will be fired.
        addQuestionPane.setValue(
            JOptionPane.UNINITIALIZED_VALUE);

        if (value.equals("Enter")) {
            String questionTypedText = questionTextField.getText();
            String mqlYesTypedText = mqlYesTextField.getText();
            String mqlNoTypedText = mqlNoTextField.getText();

            sqlModel.addQuestion(questionTypedText, mqlYesTypedText, mqlNoTypedText);
            questionTextField.setText("");
            mqlYesTextField.setText("");
            mqlNoTextField.setText("");
        } else { //user closed dialog or clicked cancel
            addQuestionDialog.setVisible(false);
        }
    }
}

我已经多次检查过代码了,我没有看到任何问题,并且对话框执行了他们应该做的事情,所以我猜测有一个特殊的addQuestion.set ...(对象我应该添加的setValue方法。

1 个答案:

答案 0 :(得分:2)

  

我是否需要为JDialog设置某个属性,以确保它在我切换窗口时保持不变。

  

我没有为它的构造函数

指定JDialog的父级

那就是问题所在。只要对话框的所有者可见,该对话框就会显示,因此您需要指定所有者JFrame。