2010-10-29 85 views
2

此外,當我點擊右上角的'X'按鈕時,對話框的行爲就好像我點擊了OK(在消息上)或YES(在問題上),當用戶點擊X時,我想要DO_Nothing。如何馴服JOptionPane對話框上的X?

在下面的代碼,當我在對話框上的X點擊,它彈出的「吃!」。顯然,X充當「YES」選項,它不應該。

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);} 
+0

什麼是你的Java版本?我無法重現OpenJDK 1.6.0_20的問題。接受的答案是使用JOptionPane的一個非常糟糕的方式。 – 2010-10-30 06:28:01

回答

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); 
} 
+0

有沒有辦法,即使我按X.沒有什麼會發生..像差點,特定actionListener。 – razshan 2010-10-29 17:21:39

+0

在代碼開始的一些代碼行中實現了這個「如果有人在對話框上按下X,就會出現不會發生的情況,我希望我的用戶完成該程序!」 – razshan 2010-10-29 17:22:16

+0

感謝它的工作,我想知道,因爲標題菜單現在幾乎沒用,有沒有辦法把它關掉。 (隱藏X,標題菜單) – razshan 2010-10-29 20:44:56

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); 
相關問題