如何在JOptionPane对话框上驯服X?

时间:2010-10-29 16:10:14

标签: java swing joptionpane

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

在下面的代码中,当我点击对话框中的X时,会弹出'eat!'。显然,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);} 

2 个答案:

答案 0 :(得分: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);
}

答案 1 :(得分: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);