JavaFX Stage 中的 WebView 大小

WebView size in JavaFX Stage

我想更改 JavaFx 应用程序 StageWebView 的大小。

我可以更改 windows 大小,但浏览器大小不会从 800px 增加,因此 html 页面的显示不适合所有 windows。

看起来像这样(注意右边的浅灰色区域):

这是页面的一些代码:

public class EfadosApp extends Application {
    private Scene scene;

    @Override public void start(Stage stage) {
        scene = new Scene(new Browser(), 1000,500);
        stage.setScene(scene);
        stage.show();
    }
}

class Browser extends Region {
    final WebView browser = new WebView();
    final WebEngine webEngine = browser.getEngine();

    public Browser() {
        webEngine.load("www.oracle.com");
        getChildren().add(browser);
    }
}

您可以简单地通过扩展 StackPane 而不是 Region:

来解决这个问题
class Browser extends StackPane {
    ...
}

不同之处在于 Region 将子项的大小调整为他们喜欢的大小:

By default a Region inherits the layout behavior of its superclass, Parent, which means that it will resize any resizable child nodes to their preferred size, but will not reposition them. If an application needs more specific layout behavior, then it should use one of the Region subclasses: StackPane, HBox, VBox, TilePane, FlowPane, BorderPane, GridPane, or AnchorPane.

虽然 StackPane 尝试调整其子项的大小以适合内容区域:

The stackpane will attempt to resize each child to fill its content area. If the child could not be sized to fill the stackpane (either because it was not resizable or its max size prevented it) then it will be aligned within the area using the alignment property, which defaults to Pos.CENTER.

这当然也意味着,如果您使用 Region,但要么将 WebViewpreferred size 设置为 "something big",例如

browser.setPrefSize(5000, 5000);

或者您将 WebViewheightPropertywidthProperty 绑定到 Stage

的相应属性
Browser browser = new Browser();
browser.browser.prefHeightProperty().bind(stage.heightProperty());
browser.browser.prefWidthProperty().bind(stage.widthProperty());
scene = new Scene(browser, 1000, 500);

它也会像您预期的那样工作。