【发布时间】:2012-07-24 15:49:39
【问题描述】:
美好的一天!
我正在使用 JavaFX SDK 开发一个程序。我想要一个像 C# 一样的消息框:
DialogResult rs = MessageBox.showDialog("Message Here...");
if (rs == ....) {
// code
}
我想使用 JavaFX SDK 来实现这样的功能。非常感谢您的回答。
【问题讨论】:
美好的一天!
我正在使用 JavaFX SDK 开发一个程序。我想要一个像 C# 一样的消息框:
DialogResult rs = MessageBox.showDialog("Message Here...");
if (rs == ....) {
// code
}
我想使用 JavaFX SDK 来实现这样的功能。非常感谢您的回答。
【问题讨论】:
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.");
}
});
【讨论】:
更新
从 Java8u40 开始,核心 JavaFX 库包括对话框(消息框)功能。请参阅以下类的文档:
有关如何使用Alert 类的快速信息,请参阅此问题的其他答案:
如需更长的教程,请参阅Makery JavaFX dialog tutorial(强烈推荐此教程)。
原答案
这是Modal Confirm 对话框的示例。它的工作原理是创建一个包含带有对话内容的场景的舞台,然后在场景上调用 show()。
如果您希望主处理线程在显示新舞台时暂停并且您使用的是 JavaFX 2.2+,那么您可以在舞台上调用 showAndWait() 而不是显示。修改为使用 show 和 wait 并仅显示消息和确定按钮,然后处理应该与 C# MessageBox 非常相似。
如果您想要一个具有专业外观的 Java 8 消息框,我建议使用 ControlsFX library 中的对话框,这是 blo0p3r 的答案中提到的 JavaFX UI 控件沙箱中对话框的后续迭代。
【讨论】:
OSS 在 JavaFX 2.2 上的 MessageBox 是 here
我想它会对你有所帮助。
MessageBox.show(primaryStage,
"Message Body",
"Message Title",
MessageBox.ICON_INFORMATION | MessageBox.OK | MessageBox.CANCEL);
【讨论】:
使用命名空间:
import javafx.scene.control.Alert;
从主线程调用:
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();
}
从非主线程调用:
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();
}
});
}
【讨论】:
这是另一个简单的替代方案:https://sites.google.com/site/martinbaeumer/programming/open-source/fxmessagebox
令人惊讶的是,JavaFX 2.2 中仍然没有可用的标准消息框
【讨论】:
这是我最终使用的,它是 JavaFX UI Controls Sandbox 的一部分,正如在 FX Experience 上宣布的 here :
这是一个不错且易于使用的对话框。无法与其他人比较,因为这是我唯一使用过的。没有问题。
代码非常简洁。看起来像这样:
//calling from a different controller and don't have the scene object loaded.
Stage stage = (Stage)deleteButton.getScene().getWindow();
DialogResponse response = Dialogs.showConfirmDialog(stage, "Are you sure ...", "Confirm deletion","Delete?", DialogOptions.OK_CANCEL);
if(response == DialogResponse.OK) {
//...
}
【讨论】:
目前我使用这个库来显示对话框。也许它对你有用:
【讨论】:
这是一个非常简单的例子: Alert alert = new Alert(AlertType.CONFIRMATION, "您确定要继续吗?");
【讨论】: