Search code examples
javafxcolumn-width

How to autoset column-width of each column header in a table


I want to autoset the column-width programatically so that the table header is fitted to its content.

@Override
public void initialize(URL url, ResourceBundle rb) {
    TableColumn<String, String> col1 = new TableColumn<>("C1");
    TableColumn<String, String> col2 = new TableColumn<>("Column 2");
    TableColumn<String, String> col3 = new TableColumn<>("Last Column (C3)");
    TableColumn<String, String> col4 = new TableColumn<>("blablabla");
    table.getColumns().add(col1);
    table.getColumns().add(col2);
    table.getColumns().add(col3);
    table.getColumns().add(col4);
    for(int i=0;i<4;i++) {
        System.out.println("Column width >> "+table.getColumns().get(i).getPrefWidth());
    }
}

The column-width of each header in a table is always set to a value of 80. How can I get and set the the width values so that the header titles are visible in each column header?


Solution

  • You can use the FontMetrics here:

    TableColumn<String, String> column1 = new TableColumn<>("C1");
        TableColumn<String, String> column2 = new TableColumn<>("Column 2");
        TableColumn<String, String> column3 = new TableColumn<>("Last Column (C3)");
        TableColumn<String, String> column4 = new TableColumn<>("blablabla");
        table.getSelectionModel().getSelectedIndex();
        table.getColumns().add(column1);
        table.getColumns().add(column2);
        table.getColumns().add(column3);
        table.getColumns().add(column4);
    
        FontMetrics fontMetrics = Toolkit.getToolkit().getFontLoader().getFontMetrics(new Font("Arial", 12));
    
        for (int i = 0; i < 4; i++) {
            String text = table.getColumns().get(i).getText();
            double textwidth =      fontMetrics.computeStringWidth(text);
            table.getColumns().get(i).setPrefWidth(textwidth + 10);
        }