Issue
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?
Solution
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);
}
}
Answered By - James_D
Answer Checked By - Marie Seifert (JavaFixing Admin)