繁体   English   中英

JavaFX 2.1 消息框

[英]JavaFX 2.1 MessageBox

再会!
我正在使用 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 对话框教程强烈推荐本教程)。

原答案

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

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

如果您想要 Java 8 的专业外观消息框,我建议使用ControlsFX 库中的对话框,这是 blo0p3r 的答案中提到的 JavaFX UI 控件沙箱中对话框的后续迭代。

OSS 的 JavaFX 2.2 上的 MessageBox 在这里

我想它会帮助你。

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控件沙盒作为宣布对外汇经验:

这是一个很好且易于使用的对话框。 无法与其他人相比,因为这是我唯一使用过的。 没有问题。

代码非常简洁。 看起来像这样:

//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) {
    //...
}

目前我使用这个库来显示对话框。 也许它对你有用:

https://github.com/4ntoine/JavaFxDialog

这是一个非常简单的例子: Alert alert = new Alert(AlertType.CONFIRMATION, "Are you sure you want to continue?");

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM