JOptionPane:parentComponent没有有效的父级 - 尝试显示错误消息

时间:2017-05-19 21:37:57

标签: java

我正在尝试使用JOptionPane对话框获取用户输入。我想在输入为空时显示错误消息,但无法获取错误消息的工作框。

if (e.getSource() == atmDone) {
        String groupName = JOptionPane.showInputDialog("Enter the group name");

        if (groupName.isEmpty()==false){
            PrintStream output;
            try {
                output = new PrintStream(new File(groupName + ".txt"));
                output.println(textArea.getText());
                output.close();

                System.out.println("here");

            } catch (FileNotFoundException e1) {
                e1.printStackTrace();
            }
        } else if (groupName.isEmpty()){
            error = new JFrame();
            JOptionPane.showInternalMessageDialog(error, "Group couldn't be saved: name empty", "Error", JOptionPane.ERROR_MESSAGE);

        }

我收到的错误表明parentComponent没有有效的父级。 我应该使用什么作为父母才能显示错误消息?

感谢。

1 个答案:

答案 0 :(得分:0)

您似乎误解了JOptionPane方法中父参数的用途。 JOptionPane或任何对话框将与其父对象关联,以便只要用户将该父窗口置于焦点,该对话框也将显示。此外,JOptionPane显示的提示对话框通常是模态到父对象,这意味着它们会阻止用户与父窗口进行交互,直到对话框关闭。

出于这些原因,始终指定有效的父级是个好主意。您的第一个JOptionPane语句应为:

String groupName = JOptionPane.showInputDialog(atmDone.getTopLevelAncestor(), "Enter the group name");

您的第二个JOptionPane调用应使用相同的父级。您看到的错误消息是由于您选择了错误的方法。名称中包含Internal的所有JOptionPane方法都需要JDesktopPane作为所提供父级的父级或祖级,因为这些方法将其对话框显示为JInternalFrame。

您可以使用名称不包含单词Internal的方法来解决问题:

JOptionPane.showMessageDialog(atmDone.getTopLevelAncestor(),
    "Group couldn't be saved: name empty", "Error", JOptionPane.ERROR_MESSAGE);