3
votes

My fxml file has the following declaration:

< TableView fx:id="myTable" prefHeight="756.0" prefWidth="472.0" />

then in Java code, I add the columns and then setItems as usual. This works as expected.

The only other code which affects the table is:

myTable.setColumnResizePolicy(TableView.CONSTRAINED_RESIZE_POLICY);

which nicely automatically re-sizes the columns. But I can't figure out how to do the following:

  1. When I add say 1 or 10 items to the table, those appear as expected in the first 1 or 10 rows of the table, but the number of rows in the table are always 21. Rest of the rows are just empty. I want the table to have only 1 row if I set 1 item or 10 rows if I set 10 items. How do I achieve this ?

  2. All the columns are of the same size. I can manually re-size them, but I want columns to auto-fit according to their size. For example if I have 2 columns one with integer from 1-10 and another with text description, they both have equal size. How do I tell it to autofit the column size according the the row contents ?

Thanks for the response!

1

1 Answers

2
votes

The table fills up the layout with empty rows. Try hiding them by adding css

.table-row-cell:empty {
    -fx-background-color: -fx-background;
}
.table-row-cell:empty .table-cell {
    -fx-border-width: 0px;
}

For #2 you can check the length of text in the cells in the cell value factory but I have title problems like that. You can read the data set and figure out what it should be. These are both approximations depending on font size.

Added this, my play cellValueFactory where I tried out some things.

    TableColumn<LineItem,String> amountCol = new TableColumn<>("Amount");
    amountCol.setPrefWidth(amountCol.getText().length()*20);
    amountCol.setCellValueFactory(new Callback<CellDataFeatures<LineItem, String>, ObservableValue<String>>() {
        @Override
        public ObservableValue<String> call(CellDataFeatures<LineItem, String> p) {
            SimpleStringProperty ssp = new SimpleStringProperty(String.format("%.4f", p.getValue().getAmount()));
            amountCol.setPrefWidth(Math.max(amountCol.getPrefWidth(), ssp.get().length()*20));
            return ssp;
        }
    });