2

また、現在、右上の「X」ボタンをクリックすると、ダイアログ ボックスは、[OK] (メッセージの場合) または [はい] (質問の場合) をクリックしたかのように動作します。ユーザーが X をクリックすると、DO_Nothing が必要になります。

以下のコードでは、ダイアログ ボックスの X をクリックすると、'eat!' が表示されます。どうやら、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);} 
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 に答える