2

另外,现在每当我点击右上角的“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);} 
4

2 回答 2

3

更改为显示如何在每个 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);
}
于 2010-10-29T16:42:55.590 回答
1

你不能通过通常的 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);
于 2010-10-29T20:14:42.900 回答