Skip to content

Instantly share code, notes, and snippets.

@dmolesUC
Created December 19, 2017 19:08
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save dmolesUC/c3148a99b4c32f7b56e20a345553b493 to your computer and use it in GitHub Desktop.
Save dmolesUC/c3148a99b4c32f7b56e20a345553b493 to your computer and use it in GitHub Desktop.
Showing only populated rows in a JavaFx TableView
import javafx.application.Application;
import javafx.beans.property.ReadOnlyObjectWrapper;
import javafx.collections.ListChangeListener;
import javafx.collections.ObservableList;
import javafx.scene.Group;
import javafx.scene.Scene;
import javafx.scene.control.TableColumn;
import javafx.scene.control.TableView;
import javafx.scene.control.skin.TableHeaderRow;
import javafx.stage.Stage;
public class TableHeightDemo extends Application {
@Override
public void start(Stage stage) {
stage.setTitle("Table height example");
TableView<String> table = new TableView<>();
table.setFixedCellSize(24); // important! (or use CSS?)
table.getItems().addListener((ListChangeListener<String>) c ->
setTableHeightByRowCount(table, c.getList()));
TableColumn<String, String> column = new TableColumn<>("name");
column.setCellValueFactory(f -> new ReadOnlyObjectWrapper<>(f.getValue()));
table.getColumns().add(column);
Group root = new Group();
root.getChildren().add(table);
Scene scene = new Scene(root);
stage.setScene(scene);
stage.show();
// Set data last to trigger our listener AFTER table header row is constructed
table.getItems().addAll("Stacey", "Kristy", "Mary Anne", "Claudia");
stage.sizeToScene();
}
private static void setTableHeightByRowCount(TableView table, ObservableList data) {
int rowCount = data.size();
TableHeaderRow headerRow = (TableHeaderRow) table.lookup("TableHeaderRow");
double tableHeight = (rowCount * table.getFixedCellSize())
// add the insets or we'll be short by a few pixels
+ table.getInsets().getTop() + table.getInsets().getBottom()
// header row has its own (different) height
+ (headerRow == null ? 0 : headerRow.getHeight());
table.setMinHeight(tableHeight);
table.setMaxHeight(tableHeight);
table.setPrefHeight(tableHeight);
}
public static void main(String[] args) {
launch(args);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment