以下にいくつかの例を示します。
Alert alert = new Alert(AlertType.WARNING, "本当に終了しますか", ButtonType.OK , ButtonType.CANCEL );//可変長引数で、使うボタンタイプを列挙 Optionalopt = alert.showAndWait(); if(opt.get() == ButtonType.OK){ System.out.println("終了"); return; }
TextInputDialog dialog = new TextInputDialog("ここに入力");
Optional msg = dialog.showAndWait();
if(msg.isPresent()) {//データがあるか?
System.out.println("入力文字列:" + msg.get());
}
ArrayListlist = new ArrayList (); list.add( "選択項目の1" ); list.add( "選択項目の2" ); list.add( "選択項目の3" ); ChoiceDialog choice = new ChoiceDialog ( list.get( 0 ) ,list ); Optional msg = choice.showAndWait(); if(msg.isPresent()){ System.out.println("選択項目の文字列:" + msg.get()); }
class MyAlert extends Alert {
public MyAlert(AlertType alertType) {
super(alertType);
this.setTitle("閉じる?");
this.setHeaderText("本当に閉じていいですか?");
this.setContentText("下のsetContentで隠れるメッセージ");
Text text1 = new Text("OKで ");
Text text2 = new Text("閉じます。");
text2.setFill(Color.BLUE);
TextFlow textFlow = new TextFlow(text1, text2);
InputStream is = this.getClass().getResourceAsStream("char.png");
Image image = new Image(is);
ImageView imageView = new ImageView(image);
VBox vbox = new VBox(4.0, textFlow, imageView);
this.getDialogPane().setContent(vbox);
}
}
以下のように使います。
Alert alert = new MyAlert(AlertType.INFORMATION); alert.showAndWait();
public class Test extends Application {
public static void main(String[] args) throws IOException {
Platform.runLater(new Runnable(){
@Override
public void run() {
Alert alert = new Alert(AlertType.WARNING);
alert.setContentText("スタートします。");
alert.showAndWait();
}
});
}
@Override
public void start(Stage primaryStage) throws Exception {
}
}
Applicationの継承クラスでないと、 java.lang.IllegalStateException の例外
(不正な状態, アプリケーションスレッドの未初期化で呼び出し)が生じます。