JOptionPane: showConfirmDialog (英語)

メソッド joptionpane.showConfirmDialog() ダイアログ ボックスに表示される小さな確認ウィンドウを作成し、ユーザーに選択の確認を求めます。たとえば、"yes" と "no" の 2 つのボタンがあるダイアログ ボックスです。

int return = showConfirmDialog(parent, message, title, typeOption, typeMessage)、または:
  • parent: は呼び出しが行われるウィンドウです。
  • message:ダイアログボックスに表示されるメッセージ。
  • title: ダイアログボックスのタイトル。
  • typeOption: 「はい」、「いいえ」、「OK」、および「キャンセル」ボタンを表示するオプション: YES_NO_OPTION、YES_NO_CANCEL_OPTION、および OK_CANCEL_OPTION;
  • typeMessage: メッセージの種類とアイコン、種類は次のとおりです。INFORMATION_MESSAGE、WARNING_MESSAGE、ERROR_MESSAGE、およびPLAIN_MESSAGE.
このメソッドは、ユーザーが選択した整数を返す関数です。以下は、showConfirmDialog():

import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JOptionPane;

public class MessageDialog {
public static void main(String[] args) {
JFrame window = new JFrame();
window.setLocationRelativeTo(null);
window.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
window.setVisible(true);
JButton leave = new JButton("Exit");
window.add(exit);
exit.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent, arg0) {
// TODO 自動生成メソッド stub
int return = showConfirmDialog();
if(return==0)//クリックしたボタンが「yes」の場合
System.exit(0);
}
});
window.add(exit);
window.pack();
}

static int showConfirmDialog(){
return JOptionPane.showConfirmDialog(
null,
"終了してもよろしいですか?",
"終了",
JOptionPane.YES_NO_OPTION);
}
}
Result:

JOptionPane: ダイアログ・ボックス showConfirmDialog

"Yes"をクリックすると、プログラムはメソッドSystem.exit(0)。それ以外の場合、「いいえ」ボタンをクリックしてもイベントは発生しません。

References:
Java2s: 確認ダイアログボックスの作成: JOptionPane Dialog
Java Doc: showConfirmDialog method