【问题标题】:How to tame the X on the JOptionPane Dialog boxes?如何驯服 JOptionPane 对话框上的 X?
【发布时间】:2010-10-29 16:10:14
【问题描述】:

另外,现在每当我点击右上角的“X”按钮时,对话框的行为就像我点击了确定(在消息上)或是(在问题上)。当用户点击 X 时,我想要 DO_Nothing。

在下面的代码中,当我单击对话框上的 X 时,它会弹出“吃!”。显然,X 正在充当“是”选项,它不应该这样做。

int c =JOptionPane.showConfirmDialog(null, "Are you hungry?", "1", JOptionPane.YES_NO_OPTION);
if(c==JOptionPane.YES_OPTION){
JOptionPane.showMessageDialog(null, "eat!", "Order",JOptionPane.PLAIN_MESSAGE);
}
else {JOptionPane.showMessageDialog(null, "ok cool", "Order",JOptionPane.PLAIN_MESSAGE);} 

【问题讨论】:

  • 你的 Java 版本是多少?我无法重现 OpenJDK 1.6.0_20 的问题。并且接受的答案是使用 JOptionPane 的一种非常糟糕的方式。

标签: java swing joptionpane


【解决方案1】:

更改为显示如何根据 OP 澄清问题来忽略对话框上的取消按钮:

JOptionPane pane = new JOptionPane("Are you hungry?", JOptionPane.QUESTION_MESSAGE, JOptionPane.YES_NO_OPTION);

JDialog dialog = pane.createDialog("Title");
dialog.addWindowListener(new WindowAdapter() {
    public void windowClosing(WindowEvent evt) {
    }
});
dialog.setContentPane(pane);
dialog.setDefaultCloseOperation(JDialog.DO_NOTHING_ON_CLOSE);
dialog.pack();

dialog.setVisible(true);
int c = ((Integer)pane.getValue()).intValue();

if(c == JOptionPane.YES_OPTION) {
  JOptionPane.showMessageDialog(null, "eat!", "Order",JOptionPane.PLAIN_MESSAGE);
}
else if (c == JOptionPane.NO_OPTION) {
  JOptionPane.showMessageDialog(null, "ok cool", "Order",JOptionPane.PLAIN_MESSAGE);
}

【讨论】:

  • 有没有办法,即使我按 X。什么也不会发生..就像那个特定的 actionListener 的障碍一样。
  • 代码开头的某行代码实现了“如果有人在对话框上按下 X,什么都不会发生,我希望我的用户完成程序!”
  • 谢谢它的工作,我想知道,因为标题菜单现在几乎没用了,有没有办法把它取下来。 (隐藏 X,标题菜单)
【解决方案2】:

你不能通过通常的 JOptionPane.show* 方法做你想做的事。

你必须这样做:

public static int showConfirmDialog(Component parentComponent,
    Object message, String title, int optionType)
{
    JOptionPane pane = new JOptionPane(message, JOptionPane.QUESTION_MESSAGE,
        optionType);
    final JDialog dialog = pane.createDialog(parentComponent, title);
    dialog.setVisible(false) ;
    dialog.setLocationRelativeTo(parentComponent);
    dialog.setDefaultCloseOperation(javax.swing.WindowConstants.DO_NOTHING_ON_CLOSE);
    dialog.setModal(true);
    dialog.setVisible(true) ;
    dialog.dispose();
    Object o = pane.getValue();
    if (o instanceof Integer) {
        return (Integer)o;
    }
    return JOptionPane.CLOSED_OPTION;
}

实际禁用关闭按钮的行是:

dialog.setDefaultCloseOperation(javax.swing.WindowConstants.DO_NOTHING_ON_CLOSE);

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2011-12-09
    • 2016-02-02
    • 1970-01-01
    • 1970-01-01
    • 2012-08-27
    • 2012-11-08
    • 1970-01-01
    相关资源
    最近更新 更多