flowpane并没有占据其外部hbox宽度的100%

mgdq6dx1  于 2021-07-03  发布在  Java
关注(0)|答案(1)|浏览(293)

这是它运行时的样子:

这是调整到全屏时的外观:

可以看到,流窗格的蓝色并没有覆盖整个hbox的红色。
如何使流窗格跨度达到hbox宽度的100%,同时保持hbox在网格内居中,流窗格在hbox和flowpane&hbox内居中,并在窗口调整大小时自动调整大小?所以字母c和d至少适合小窗口中的第一个raw,所有字母适合大窗口。

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

public class TestFlowPane extends Application {
    private GridPane gridPane;
    private Scene scene;

    @Override
    public void start(Stage applicationStage) {
        gridPane = new GridPane();
        scene = new Scene(gridPane, 500, 400);
        ColumnConstraints column = new ColumnConstraints();
        column = new ColumnConstraints();
        column.setPercentWidth(100);
        gridPane.setAlignment(Pos.CENTER);
        gridPane.getColumnConstraints().add(column);

        gridPane.setPrefSize(500, 400);
        gridPane.setMaxSize(Region.USE_COMPUTED_SIZE, Region.USE_COMPUTED_SIZE);

        gridPane.setPadding(new Insets(5, 20, 20, 20));
        gridPane.setHgap(10);
        gridPane.setVgap(10);

        HBox panelBox = new HBox();
        panelBox.setStyle( "-fx-background-color:   red; ");
        panelBox.setSpacing(20);
        panelBox.setAlignment(Pos.CENTER);
        FlowPane flowPane = new FlowPane();
        flowPane.setStyle( "-fx-background-color:   blue; ");

        String[] names = {"AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA", "BBBBBBBBBBBBB", "C", "D", "E"};
        for (String n: names) {
            Label label = new Label(n);
            label.setStyle( "-fx-text-fill:   white; ");
            flowPane.getChildren().add(label);
        }
        flowPane.setHgap(5);
        flowPane.setVgap(10);
        panelBox.getChildren().add(flowPane);
        gridPane.add(panelBox, 0, 0);

        applicationStage.setScene(scene);
        applicationStage.show();
    }
}
wmtdaxz3

wmtdaxz31#

您需要添加:

HBox.setHgrow(flowPane, Priority.ALWAYS);

之后

panelBox.getChildren().add(flowPane);

这就行了

相关问题