Reputation: 1525
A minor graphical annoyance but I have a ListView set to display custom objects with a set height more than the default. I attempted to use setFixedCellSize()
which works perfectly in most uses but in one case the cell heights for some cells may grow and shrink based on user interaction.
class Example extends Label {
private boolean change = true;
public Example(String text) {
super(text);
setMinHeight(150);
setPrefHeight(150);
setMaxHeight(150);
Hyperlink link = new Hyperlink("Change");
setGraphic(link);
link.setOnAction(ae -> {
change = !change;
if(change) {
setMinHeight(80);
setPrefHeight(80);
setMaxHeight(80);
} else {
setMinHeight(180);
setPrefHeight(180);
setMaxHeight(180);
}
});
}
}
ListView<Node> list = new ListView<>();
list.setFixedCellSize(150);
list.getSelectionModel().setSelectionMode(SelectionMode.MULTIPLE);
list.getItems().addAll(new Example("Hello world"), new Example("12345"));
In my example above, the label changes height when the Hyperlink is clicked. It no longer does this when setFixedCellSize()
is added. Is there another way achieve the same effect of changing the dummy rows but allow the custom Nodes to change height?
Upvotes: 2
Views: 3275
Reputation: 6911
You can set a custom cell factory which sets your desired height based on the state of the cell (I'm assuming by "dummy cells" you mean empty cells):
ListView<String> lv = new ListView<>();
lv.setCellFactory(lst ->
new ListCell<String>() {
@Override
protected void updateItem(String item, boolean empty) {
super.updateItem(item, empty);
if (empty) {
setPrefHeight(45.0);
setText(null);
} else {
setPrefHeight(Region.USE_COMPUTED_SIZE);
setText(item);
}
}
});
lv.getItems().addAll("Hello", "World");
This will cause non-empty cells to have their preferred size (according to the content, in this case it's just the string), while empty cells will have their preferred size as 45.
Upvotes: 6