JavaFX 2.1 MessageBox

iSa*_*iSa 11 java javafx javafx-2

美好的一天!
我正在使用JavaFX SDK开发一个程序.我想在C#中有一个消息框:

DialogResult rs = MessageBox.showDialog("Message Here...");
if (rs == ....) {
    // code
}
Run Code Online (Sandbox Code Playgroud)

我希望使用JavaFX SDK获得这样的功能.答案非常感谢.

Lim*_*ent 18

https://docs.oracle.com/javase/8/javafx/api/javafx/scene/control/Alert.html

Alert类是Dialog类的子类,并为许多预构建的对话框类型提供支持,这些类型可以很容易地显示给用户以提示响应.

所以代码看起来像

Alert alert = new Alert(AlertType.INFORMATION);
alert.setTitle("Message Here...");
alert.setHeaderText("Look, an Information Dialog");
alert.setContentText("I have a great message for you!");
alert.showAndWait().ifPresent(rs -> {
    if (rs == ButtonType.OK) {
        System.out.println("Pressed OK.");
    }
});
Run Code Online (Sandbox Code Playgroud)


jew*_*sea 6

更新

从Java8u40开始,核心JavaFX库包括对话框(消息框)功能.请参阅以下类的文档:

原始答案

以下是" 模态确认"对话框的示例.它的工作原理是创建一个包含场景的舞台,其中包含对话框内容,然后在场景中调用show().

如果您希望在显示新舞台并且使用JavaFX 2.2+时暂停主处理线程,则可以在舞台上调用showAndWait()而不是show.修改为使用show和wait,只显示一条消息和ok按钮,然后处理应该与C#MessageBox非常相似.

如果你想要一个专业的Java 8消息框,我建议使用来自ControlsFX库的对话框,这是后来在blo0p3r的答案中提到的JavaFX UI Controls Sandbox中对话框的迭代.


And*_*ski 5

使用命名空间:

import javafx.scene.control.Alert;
Run Code Online (Sandbox Code Playgroud)

从主线程调用:

public void showAlert() { 
    Alert alert = new Alert(Alert.AlertType.INFORMATION);
    alert.setTitle("Message Here...");
    alert.setHeaderText("Look, an Information Dialog");
    alert.setContentText("I have a great message for you!");
    alert.showAndWait();
}
Run Code Online (Sandbox Code Playgroud)

从非主线程调用:

public void showAlert() {
    Platform.runLater(new Runnable() {
      public void run() {
          Alert alert = new Alert(Alert.AlertType.INFORMATION);
          alert.setTitle("Message Here...");
          alert.setHeaderText("Look, an Information Dialog");
          alert.setContentText("I have a great message for you!");
          alert.showAndWait();
      }
    });
}
Run Code Online (Sandbox Code Playgroud)