JavaFX警报及其大小

最近,JavaFX引入了Alerts(Java 8u40)。

考虑下面的代码示例。 如何显示超过几个字的完整消息? 我的消息( contentText属性)最后被切断了...而且我认为警报没有正确调整其大小。

在我的带有Oracle JDK 8u40的Linux机器上,我只看到文本This is a long text. Lorem ipsum dolor sit amet This is a long text. Lorem ipsum dolor sit amet ,在某些情况下太短了。

当然,用户可以手动调整警报窗口的大小,并相应地显示文本,但这根本不是用户友好的。

编辑:Windows 7和Linux的屏幕截图(来自Oracle的JDK): Windows警报Linux警报

 import javafx.application.Application; import javafx.scene.control.Alert; import javafx.scene.control.Alert.AlertType; import javafx.stage.Stage; public class TestAlert extends Application { public static void main(String[] args) { launch(args); } @Override public void start(Stage primaryStage) throws Exception { Alert a = new Alert(AlertType.INFORMATION); a.setTitle("My Title"); a.setHeaderText("My Header Text"); a.setResizable(true); String version = System.getProperty("java.version"); String content = String.format("Java: %s.\nThis is a long text. Lorem ipsum dolor sit amet, consetetur sadipscing elitr, sed diam nonumy eirmod tempor invidunt ut labore et dolore magna aliquyam erat, sed diam voluptua. At vero eos et accusam et justo duo dolores et ea rebum. Stet clita kasd gubergren, no sea takimata sanctus est Lorem ipsum dolor sit amet. Lorem ipsum dolor sit amet, consetetur sadipscing elitr, sed diam nonumy eirmod tempor invidunt ut labore et dolore magna aliquyam erat, sed diam voluptua. At vero eos et accusam et justo duo dolores et ea rebum. Stet clita kasd gubergren, no sea takimata sanctus est Lorem ipsum dolor sit amet.", version); a.setContentText(content); a.showAndWait(); } } 

我做了以下解决方法:

 Alert alert = new Alert(AlertType.INFORMATION, "Content here", ButtonType.OK); alert.getDialogPane().setMinHeight(Region.USE_PREF_SIZE); alert.show(); 

因此窗口将根据内容自动resize。

这是没有幻数,resize等更好的解决方法:

 Alert alert = new Alert(AlertType.ERROR, "content text"); alert.getDialogPane().getChildren().stream().filter(node -> node instanceof Label).forEach(node -> ((Label)node).setMinHeight(Region.USE_PREF_SIZE)); 

此解决方案适用于Windows,Linux和Mac。

我之前做过以下解决方法:

 Alert dialog = new Alert(Alert.AlertType.ERROR); dialog.setHeaderText("Connection Failed"); dialog.setContentText(this.getException().getMessage()); //FIXME: Remove after release 8u40 dialog.setResizable(true); dialog.getDialogPane().setPrefSize(480, 320); dialog.showAndWait(); 

如您所见,我只需设置可resize的标志并设置首选大小。

但这很奇怪,因为这个bug 应该在8u40中修复。 您使用的是8u40的最新版本吗?

更新

未在8u40中修复。 应该稍后修复 。

另一种解决方案是对Alert进行子类化并在那里应用所需的样式,例如:

 class SubAlert extends Alert { { setHeaderText(""); getDialogPane().getStylesheets().add("some_stylesheet"); getDialogPane().getStyleClass().add("style_class"); getDialogPane().setMinHeight(Region.USE_PREF_SIZE); } SubAlert(AlertType alertType) { super(alertType); } SubAlert(AlertType type,String title,String content) { super(type); setTitle(title); setContentText(content); } } 

这样,您就不必为您创建的每个警报重复操作。