1

ユーザーから 2 つの文字列を収集するカスタム ダイアログ ボックスがあります。ダイアログを作成するとき、オプション タイプに OK_CANCEL_OPTION を使用します。ユーザーがキャンセルをクリックするか、ダイアログを閉じた場合を除いて、すべてが機能します。これは、[OK] ボタンをクリックした場合と同じ効果があります。

キャンセル イベントとクローズ イベントを処理するにはどうすればよいですか?

私が話しているコードは次のとおりです。

JTextField topicTitle = new JTextField();
JTextField topicDesc = new JTextField();
Object[] message = {"Title: ", topicTitle, "Description: ", topicDesc};
JOptionPane pane = new JOptionPane(message,  JOptionPane.PLAIN_MESSAGE, JOptionPane.OK_CANCEL_OPTION);
JDialog getTopicDialog =  pane.createDialog(null, "New Topic");
getTopicDialog.setVisible(true);

// OK が押されたときにここで何かを実行し、キャンセルが押されたときに破棄します。

/注: この問題についてJOptionPane.ShowOptionDialog( ** * ** );**の方法を提案しないでください。私はその方法を知っていますが、上記の方法で「OK」と「」のアクションを設定する必要があります。 CANCEL」ボタン*/

4

2 に答える 2

4

これは私のために働きます:

...
JOptionPane pane = new JOptionPane(message,  JOptionPane.PLAIN_MESSAGE, JOptionPane.OK_CANCEL_OPTION);
JDialog getTopicDialog =  pane.createDialog(null, "New Topic");
getTopicDialog.setVisible(true);
if(null == pane.getValue()) {
    System.out.println("User closed dialog");
}
else {
    switch(((Integer)pane.getValue()).intValue()) {
    case JOptionPane.OK_OPTION:
        System.out.println("User selected OK");
        break;
    case JOptionPane.CANCEL_OPTION:
        System.out.println("User selected Cancel");
        break;
    default:
        System.out.println("User selected " + pane.getValue());
    }
}
于 2013-02-05T08:22:57.127 に答える
1

ドキュメントによると、どのボタンがクリックされたかを知るために pane.getValue() を使用できます。ドキュメントから:

直接使用: JOptionPane を直接作成して使用するための標準的なパターンは、おおよそ次のとおりです。

     JOptionPane pane = new JOptionPane(arguments);
     pane.set.Xxxx(...); // Configure
     JDialog dialog = pane.createDialog(parentComponent, title);
     dialog.show();
     Object selectedValue = pane.getValue();
     if(selectedValue == null)
       return CLOSED_OPTION;
     //If there is not an array of option buttons:
     if(options == null) {
       if(selectedValue instanceof Integer)
          return ((Integer)selectedValue).intValue();
       return CLOSED_OPTION;
     }
     //If there is an array of option buttons:
     for(int counter = 0, maxCounter = options.length;
        counter < maxCounter; counter++) {
        if(options[counter].equals(selectedValue))
        return counter;
     }
     return CLOSED_OPTION;

それが役に立てば幸い、

于 2013-02-05T08:14:41.260 に答える