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?
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);
}
}
The TableView
s columnResizePolicy
is your friend:
If you set TableView.setColumnResizePolicy(TableView.CONSTRAINED_RESIZE_POLICY)
all columns will be equally resized until the TableView
s 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
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With