如何修复 javafx - tableview 大小为当前 window 大小

how to fix javafx - tableview size to current window size

我对独立应用程序完全陌生。请任何人帮助我。

我有 6 列的 TableView,其中一半显示在 window 中,如下所示。

我想修复它当前的 window 大小,即使 window 展开时,tableview 也应该自动调整大小。有什么办法吗?

这是代码片段

GridPane tableGrid= new GridPane();
tableGrid.setVgap(10);
tableGrid.setHgap(10);
Label schoolnameL= new Label(SCHOOL+school_id);
schoolnameL.setId("schoolLabel");
Button exportDataSheetBtn= new Button("Export In File");
tableView.setMaxWidth(Region.USE_PREF_SIZE);
tableView.setColumnResizePolicy(TableView.CONSTRAINED_RESIZE_POLICY);
tableGrid.getChildren().addAll(schoolnameL,exportDataSheetBtn,tableView);

这可以通过将首选高度和宽度绑定到主舞台的高度和宽度来完成。这是一个 MCVE:

import javafx.application.Application;
import javafx.collections.ObservableList;
import javafx.scene.Scene;
import javafx.scene.control.TableView;
import javafx.stage.Stage;

public class MCVE extends Application {

    @Override
    public void start(Stage stage) {

        TableView<ObservableList<String>> table = new TableView<ObservableList<String>>();

        // We bind the prefHeight- and prefWidthProperty to the height and width of the stage.
        table.prefHeightProperty().bind(stage.heightProperty());
        table.prefWidthProperty().bind(stage.widthProperty());

        stage.setScene(new Scene(table, 400, 400));
        stage.show();
    }

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

}

您可以使用 ScrollPane 作为场景的根,并将其他所有内容放入其中。然后将 属性 setFitToWidth 和 setFitToHeight 设置为 true,ScrollPane 内的所有内容将被拉伸以适合 ScrollPane 大小,并且 ScrollPane 将适合场景,因为它是布局窗格。如果用户将 window 的大小调整为小于内容的最小宽度,它也会显示滚动条,因此内容不会被截断!

@Override
public void start(Stage stage) {

    TableView<ObservableList<String>> table = new TableView<ObservableList<String>>();
    table.setMinWidth(400);

    ScrollPane sp = new ScrollPane(table);
    sp.setFitToHeight(true);
    sp.setFitToWidth(true);

    stage.setScene(new Scene(table, 800, 600));
    stage.show();
}

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

我从 Jonathan 的回答中复制了部分 MCVE,希望你不要介意 Jonathan :)

有关制作可调整大小的 GUI 的更多一般提示,请查看此 post

在 GridPane 中创建 Tabel 并在 AnchorPane.Click 中使用 GridePane on GridPane(capture1)。 单击 GridPane 布局 (captur2) 中的 Ancho Pane Constraint。

在 table 中查看布局 select Hgrow 和 Vgrow 为 'Always'(capture3)

VBox.setVgrow(tableView, Priority.ALWAYS);

或者您的父级布局:

 VBox.setVgrow({{PARENT}}, Priority.ALWAYS);

它为我修复了: