Reputation: 588
In my ListView myList, I want each item(String) to have a mini photo next to it.
Here is my how my ListView myList is defined:
ListView<String> myList = new ListView<String>();
SearchResultList.setCellFactory(new Callback<ListView<String>,ListCell<String>>() {
@Override
public ListCell<String> call(ListView<String> list) {
return new ColorRectCell();
}
}
);
I read you must specify a cell factory which updates each item in list. However I don't know how this all works, This is the code where I specify my cell factory
static class ColorRectCell extends ListCell<String> {
@Override
public void updateItem(String item, boolean empty) {
super.updateItem(item, empty);
Image rect = new Image("huisteken.jpg");
ImageView rec = new ImageView(rect);
if (item != null) {
System.out.println("testing" + item +"######");
setGraphic(rec);
setContentDisplay(ContentDisplay.GRAPHIC_ONLY);
}
}
}
Please, any ideas or tips are welcome.
Upvotes: 1
Views: 935
Reputation: 635
My solution to accomplish this is to set the Cells text to null and to make Graphic contain a Hbox containing both picture and text. So make your updateItem look like this:
@Override
void updateItem(final String item, final boolean empty) {
super.updateItem(item, empty);
// if null, display nothing
if (empty || item == null) {
setText(null);
setGraphic(null);
return;
}
setText(null);
Label textLabel = new Label(item + " ");
final HBox hbox = new HBox();
hbox.setSpacing(5);
Label iconLabel = new Label();
iconLabel.setGraphic(new ImageView(new Image("huisteken.jpg")));
hbox.getChildren().addAll(iconLabel, textLabel);
setGraphic(hbox);
}
`
Upvotes: 1