如何获取 TableView 列的大小?

How to get size of TableView column?

有什么方法可以获取 TableView 列的当前大小?我什至无法在网上找到问题,这让我觉得我错过了一些东西,因为我不是第一个需要此功能的人。

如果这不可能,是否有任何方法可以设置 TableView 列的大小?这也可以解决我的问题,尽管我更愿意获得尺寸。 setFixedCellSize(double) 看起来很有希望,但我无法让它发挥作用。

我希望在我的 TableView 中的每一列上方都有一个 TextField,其大小与其上方的列相同。如果有更好的方法来实现这一点,我愿意接受建议。

您可以使用 Property-Bindings。但是 TableColumn 或 TextField 的 width-属性 是只读的。这是正确的,因为宽度和高度是呈现整个 window.

布局过程的一部分

因此您需要为 TextField 设置三个大小,最小 - 首选 - 最大宽度,当前宽度来自 TableColumn。在我看来,将 TableColumns 宽度作为 TextFields 宽度的主要方式是首选方法。

现在,即使手动调整大小,您的 TextField 仍保持与 "bound" TableColumns 宽度相同的宽度。

下面有点Minimal, Complete, and Verifiable example:

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


public class TableTest extends Application {

  @Override
  public void start(Stage primaryStage) {
    TextField field = new TextField();

    TableView<String> table = new TableView<>();
    TableColumn<String, String> column = new TableColumn("Header Text");
    table.getColumns().add(column);

    field.prefWidthProperty().bind(column.widthProperty());
    field.minWidthProperty().bind(column.widthProperty());
    field.maxWidthProperty().bind(column.widthProperty());

    VBox root = new VBox();
    root.getChildren().addAll(field, table);

    Scene scene = new Scene(root, 300, 250);

    primaryStage.setTitle("Hello World!");
    primaryStage.setScene(scene);
    primaryStage.show();
  }

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