首页 > 解决方案 > 在 JavaFX 的 layoutBounds 中包含比例因子

问题描述

我正在使用 JavaFx 8。

从 JavaDoc 的javafx.scene.Node.scaleYProperty()

[...] 默认情况下,layoutBounds 中不包含此比例因子,这使得它非常适合在考虑所有效果和变换后缩放整个节点。[...]

但是,如何在 layoutBounds 中包含缩放因子

一些上下文:在下面的示例中,当按下按钮时,我希望 GridPane 也对 HBox 的缩放做出反应,而不必对 RowConstraints 的 prefHeight 进行硬编码。

能够将缩放因子包含在 layoutBounds 中可能会起到作用,但也欢迎其他解决方案。

import javafx.application.Application;
import javafx.geometry.Pos;
import javafx.scene.Scene;
import javafx.scene.control.Label;
import javafx.scene.control.ToggleButton;
import javafx.scene.layout.*;
import javafx.stage.Stage;

public class ScalingStandAlone extends Application {

    private VBox vBox = new VBox();
    private GridPane gridPane = new GridPane();
    private HBox  hBox = new HBox();
    private ToggleButton button = new ToggleButton("Click to scale");
    private Label firstRowLabel = new Label("Some content in text form");
    private Label secondRowLabel = new Label("Some content for scaling");
    private Label thirdRowLabel = new Label("Some moving content");

    public static void main(String[] args) {
        Application.launch(args);
    }

    @Override
    public void start(Stage stage) throws Exception {
        AnchorPane root = new AnchorPane();
        AnchorPane.setTopAnchor(vBox, 5.);
        AnchorPane.setLeftAnchor(vBox, 5.);
        AnchorPane.setRightAnchor(vBox, 5.);
        root.autosize();
        Scene scene = new Scene(root);
        stage.setTitle("GridRow Scale Demo");
        stage.setWidth(400);
        stage.setHeight(300);
        stage.setScene(scene);
        stage.show();

        root.getChildren().add(vBox);
        vBox.setAlignment(Pos.CENTER);
        vBox.getChildren().add(gridPane);
        vBox.getChildren().add(button);
        vBox.setStyle("-fx-spacing: 15;");

        configureGridPane(root);

        button.setOnAction(event -> {
            hBox.setScaleY(button.isSelected() ? 2 : 1);
        });
    }

    private void configureGridPane(Pane root) {
        hBox.getChildren().add(secondRowLabel);

        // Styling //
        firstRowLabel.setStyle("-fx-padding: 5;");
        hBox.setStyle("-fx-background-color: #800000; -fx-padding: 5;");
        secondRowLabel.setStyle("-fx-text-fill: white; -fx-padding: 5;");
        thirdRowLabel.setStyle("-fx-padding: 5;");

        gridPane.add(firstRowLabel, 0, 0);
        gridPane.add(hBox, 0, 1);
        gridPane.add(thirdRowLabel, 0, 2);
        gridPane.setGridLinesVisible(true);
        gridPane.getColumnConstraints().add(new ColumnConstraints());
        gridPane.getColumnConstraints().get(0).setPercentWidth(100);
    }
}

标签: javajavafxlayout

解决方案


来自Javadocs 的Group

应用于组的任何变换、效果或状态都将应用于该组的所有子项。此类变换和效果不会包含在此 Group 的布局边界中,但是如果直接在此 Group 的子级上设置变换和效果,则这些变换和效果将包含在此 Group 的布局边界中。

(我的重点补充说)。

因此,如果您简单地将您的包装HBox在 a 中Group,您将达到预期的效果:

    // gridPane.add(hBox, 0, 1);
    gridPane.add(new Group(hBox), 0, 1);

推荐阅读