如何将JavaFX的TableView大小调整为当前窗口大小

8
我是一个全新的独立应用程序用户。请有人帮助我。
我有一个TableView,其中有6列,但只显示了一半,如下所示。

enter image description here

我希望固定当前窗口大小,即使窗口扩展,表格视图也应自动调整大小。有没有办法做到这一点? 以下是代码片段
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);

添加一些与TableView及其父容器相关的代码将有助于我们更好地帮助您。 - ItachiUchiha
4个回答

11

可以通过将首选高度和宽度绑定到主舞台的高度和宽度来实现。这是一个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();
    }

}

4
在GridPane内创建表格,并在AnchorPane内使用GridPane。点击GridPane(capture1)。 enter image description here 在GridPane布局中选择Ancho Pane约束(captur2)。 enter image description here 在table view布局中,将Hgrow和Vgrow设置为“始终”(capture3) enter image description here

这对我有用 - 我所需要做的就是设置Hgrow和Vgrow,谢谢。 - Filip
同样适用于ArchonePane - undefined

4
VBox.setVgrow(tableView, Priority.ALWAYS);

或者针对您的父布局:

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

对我来说它已经修复了:

enter image description here

enter image description here


0
您可以使用ScrollPane作为场景的根,并将所有其他内容放在其中。然后将属性setFitToWidth和setFitToHeight设置为true,ScrollPane内部的所有内容都将被拉伸以适应ScrollPane的大小,并且ScrollPane将适合于Scene,因为它是一个Layout Pane。如果用户将窗口调整为小于内容的minWidth,则还会显示滚动条,以防止内容被截断!
@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的更一般提示,请查看此文章


更像是一种权宜之计,而不是一个解决方案。 - undefined

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接