NaveenBharadwaj
NaveenBharadwaj

Reputation: 1333

How to set column width in tableview in javafx?

I have a table with two columns. I should set the width to 30% and 70%. The table is expandable but not columns. How do I achieve that?

Upvotes: 15

Views: 40871

Answers (2)

James_D
James_D

Reputation: 209225

If by "the table is expandable but not the columns", you mean the user should not be able to resize the columns, then call setResizable(false); on each column.

To keep the columns at the specified width relative to the entire table width, bind the prefWidth property of the columns.

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);
    }
}

Upvotes: 27

eckig
eckig

Reputation: 11134

The TableViews columnResizePolicy is your friend:

If you set TableView.setColumnResizePolicy(TableView.CONSTRAINED_RESIZE_POLICY) all columns will be equally resized until the TableViews maximum width is reached.

Additionally you can write your own policy: The policy is just a Callback where ResizeFeatures is given as input from where you have access to the TableColumn.

Upvotes: 23

Related Questions