在JOptionPane中禁用关闭x

时间:2009-11-20 20:02:29

标签: java joptionpane

我想禁用我的JOptionPane左上角的关闭x我该怎么做?

4 个答案:

答案 0 :(得分:4)

迈克尔,

我不知道如何禁用关闭[x]按钮。或者,当用户点击它时,您什么都不做。检查以下代码:

JOptionPane pane = new JOptionPane("message");
JDialog dialog = pane.createDialog(null, "Title");
dialog.setDefaultCloseOperation(WindowConstants.DO_NOTHING_ON_CLOSE);
dialog.setVisible(true);

对你来说是否合理?

答案 1 :(得分:2)

您可以通过JOptionPane中声明的取消按钮覆盖退出按钮并相应地处理取消操作:

JOptionPane optionPane= new JOptionPane("message", JOptionPane.OK_CANCEL_OPTION);

final JDialog dialog = optionPane.createDialog(null, "Input");
dialog.setDefaultCloseOperation(JDialog.DO_NOTHING_ON_CLOSE);
dialog.addWindowListener(new WindowAdapter() { 
@Override public void windowClosing(WindowEvent e) { 
    optionPane.setValue(JOptionPane.CANCEL_OPTION);
}
});

if (JOptionPane.CANCEL_OPTION!= ((Integer) optionPane.getValue()).intValue())
                    throw new myCancellationException();

答案 2 :(得分:1)

当用户尝试关闭对话框而不选择选项时,您可以随时再次显示该对话框。有一个如何覆盖sun.com处的默认结束行为的示例。在“停止自动对话关闭”下查看,它们具有以下代码:

final JOptionPane optionPane = new JOptionPane(
                "The only way to close this dialog is by\n"
                + "pressing one of the following buttons.\n"
                + "Do you understand?",
                JOptionPane.QUESTION_MESSAGE,
                JOptionPane.YES_NO_OPTION);

final JDialog dialog = new JDialog(frame, 
                             "Click a button",
                             true);
dialog.setContentPane(optionPane);
dialog.setDefaultCloseOperation(
    JDialog.DO_NOTHING_ON_CLOSE);
dialog.addWindowListener(new WindowAdapter() {
    public void windowClosing(WindowEvent we) {
        setLabel("Thwarted user attempt to close window.");
    }
});

optionPane.addPropertyChangeListener(
    new PropertyChangeListener() {
        public void propertyChange(PropertyChangeEvent e) {
            String prop = e.getPropertyName();

            if (dialog.isVisible() 
             && (e.getSource() == optionPane)
             && (prop.equals(JOptionPane.VALUE_PROPERTY))) {
                //If you were going to check something
                //before closing the window, you'd do
                //it here.
                dialog.setVisible(false);
            }
        }
    });
dialog.pack();
dialog.setVisible(true);

int value = ((Integer)optionPane.getValue()).intValue();
if (value == JOptionPane.YES_OPTION) {
    setLabel("Good.");
} else if (value == JOptionPane.NO_OPTION) {
    setLabel("Try using the window decorations "
             + "to close the non-auto-closing dialog. "
             + "You can't!");
}

使用该代码,您可以轻松调整评论部分,以便仅在用户单击其中一个可用选项而非关闭按钮时关闭窗口。

答案 3 :(得分:0)

我不确定是否有办法在JOptionPane中执行此操作。

通常当人们想要比JOptionPane提供的更多灵活性时(它基本上是一些用于几个对话框的静态工厂),他们使用JDialog编写自己的对话框。

JDialog提供了继承的方法setUndecorated,它完全消除了 X 。这是更多的工作,但你可以让你的对话看起来你想要的。

相关问题