JavaFX 2.1 MessageBox
美好的一天!
我正在使用JavaFX SDK开发一个程序。 我想在C#中有一个消息框:
DialogResult rs = MessageBox.showDialog("Message Here..."); if (rs == ....) { // code }
我想使用JavaFX SDK获得这样的function。 答案非常感谢。
更新
从Java8u40开始,核心JavaFX库包括对话框(消息框)function。 请参阅以下类的文档:
- 警报
- 对话框 (和子类)
原始答案
以下是“ 模态确认”对话框的示例。 它的工作原理是创建一个包含场景的舞台,其中包含对话框内容,然后在场景中调用show()。
如果您希望在显示新舞台并且您使用JavaFX 2.2+时暂停主处理线程,则可以在舞台上调用showAndWait()而不是show。 修改为使用show和wait并只显示一条消息和ok按钮,然后处理应该与C#MessageBox非常相似。
如果你想要一个专业的Java 8消息框,我建议使用来自ControlsFX库的对话框,这是后来在blo0p3r的答案中提到的JavaFX UI Controls Sandbox中对话框的迭代。
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."); } });
OSS的JavaFX 2.2上的MessageBox就在这里
我认为它会对你有所帮助。
MessageBox.show(primaryStage, "Message Body", "Message Title", MessageBox.ICON_INFORMATION | MessageBox.OK | MessageBox.CANCEL);
这是另一个简单的替代方案: https : //sites.google.com/site/martinbaeumer/programming/open-source/fxmessagebox
令人惊讶的是,JavaFX 2.2中仍然没有可用的标准消息框
这就是我最终使用的内容,这是在FX Experience上宣布的JavaFX UI Controls Sandbox的一部分:
- 链接到教程: http : //code.makery.ch/blog/javafx-2-dialogs
- 链接到源代码: https : //github.com/marcojakob/javafx-ui-sandbox/tree/master/javafx-dialogs
这是一个很好用且易于使用的对话框。 无法与其他人比较,因为这是我用过的唯一一个。 没问题。
代码非常简洁。 看起来像这样:
//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) { //... }
使用命名空间:
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(); } }); }
目前我使用这个库来显示Dialogs。 也许它对你有用:
这是一个非常简单的示例:警报警报=新警报(AlertType.CONFIRMATION,“您确定要继续吗?”);