Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to set column width in tableview in javafx?

Tags:

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?

like image 826
NaveenBharadwaj Avatar asked Feb 10 '15 09:02

NaveenBharadwaj


Video Answer


2 Answers

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);
    }
}
like image 166
James_D Avatar answered Oct 17 '22 19:10

James_D


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.

like image 18
eckig Avatar answered Oct 17 '22 18:10

eckig