Created
December 19, 2017 19:08
-
-
Save dmolesUC/c3148a99b4c32f7b56e20a345553b493 to your computer and use it in GitHub Desktop.
Showing only populated rows in a JavaFx TableView
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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