如何在 javafx 的 tableview 中设置列​​宽?

How to set column width in tableview in javafx?

我有一个包含两列的 table。我应该将宽度设置为 30% 和 70%。 table 是可扩展的,但不是列。我该如何实现?

TableViewcolumnResizePolicy是你的朋友:

如果您设置 TableView.setColumnResizePolicy(TableView.CONSTRAINED_RESIZE_POLICY),所有列的大小都将相同,直到达到 TableView 的最大宽度。

此外,您可以编写自己的政策:该政策只是一个 Callback,其中 ResizeFeatures 作为输入,您可以从那里访问 TableColumn.

如果 "the table is expandable but not the columns",你的意思是用户不应该能够调整列的大小,然后在每一列上调用 setResizable(false);

要使列保持相对于整个 table 宽度的指定宽度,请绑定列的 prefWidth 属性。

SSCCE:

import javafx.application.Application;
import javafx.scene.Scene;
import javafx.scene.control.TableColumn;
import javafx.scene.control.TableView;
import javafx.scene.layout.BorderPane;
import javafx.stage.Stage;

public class TableColumnResizePolicyTest extends Application {

    @Override
    public void start(Stage primaryStage) {
        TableView<Void> table = new TableView<>();
        TableColumn<Void, Void> col1 = new TableColumn<>("One");
        TableColumn<Void, Void> col2 = new TableColumn<>("Two");
        table.getColumns().add(col1);
        table.getColumns().add(col2);

        col1.prefWidthProperty().bind(table.widthProperty().multiply(0.3));
        col2.prefWidthProperty().bind(table.widthProperty().multiply(0.7));

        col1.setResizable(false);
        col2.setResizable(false);

        primaryStage.setScene(new Scene(new BorderPane(table), 600, 400));
        primaryStage.show();
    }

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