Reputation: 41
I would like to add a photo to each item in a ComboBox
so when the user hovers over the name of that item in the ComboBox
, the photo of that item will be displayed.
Here is my code:
lights.setConverter(new StringConverter<Light>() {
@Override
public String toString(Light object) {
return object.getName();
}
@Override
public Light fromString(String string) {
return null;
}
});
lights.setItems(FXCollections.observableArrayList
(new Light ("Incandescent", 5.23),
new Light ("Halogen", 5.75),
new Light ("fluorescent",7.29),
new Light ("Compact fluorescent bulbs",4.83),
new Light ("LED",4.83)));
lights.setPromptText("Please select a light");
lights.setPrefWidth(100);
lights.valueProperty().addListener((obs, oldVal, newVal) -> {
String selectionText = "The price for the " + newVal.getName() + " light is : $" + newVal.getPrice();
lightNamePrice.setText(selectionText);
});
private class Light {
private String name;
private Double price;
private Double getPrice() {
return price;
}
private String getName() {
return name;
}
private Light(String name, Double price) {
this.name = name;
this.price = price;
}
}
Anyone got any ideas? I am fairly new at JavaFX so any help I can get will be great.
Upvotes: 4
Views: 2065
Reputation: 21799
You could use setCellFactory
method of your ComboBox
to customize the rendering of the items in the drop-down list in a way to return a ListCell
which has a Tooltip
attached as ListCell
is a subclass of Control
therefore it provides setTooltip
method.
Example
I have updated the Light
class to make every instance of this class able to have its own image:
private class Light {
private String name;
private Double price;
private Image image;
public Image getImage() {
return image;
}
private Double getPrice() {
return price;
}
private String getName() {
return name;
}
private Light(String name, Double price, Image image) {
this.name = name;
this.price = price;
this.image = image;
}
}
Then I have updated the code which fills up the data to use the (same) Image
:
Image image = new Image(getClass().getResource("light.png").toExternalForm(), 100, 100, true, true);
lights.setItems(FXCollections.observableArrayList
(new Light ("Incandescent", 5.23, image),
new Light ("Halogen", 5.75, image),
new Light ("fluorescent",7.29, image),
new Light ("Compact fluorescent bulbs",4.83, image),
new Light ("LED",4.83, image)));
Then finally the update on the cell factory:
lights.setCellFactory(param -> {
return new ListCell<Light>() {
@Override
public void updateItem(Light item, boolean empty) {
super.updateItem(item, empty);
if (item != null) {
setText(item.getName());
// Add the Tooltip with the image of the current item
Tooltip tt = new Tooltip();
tt.setGraphic(new ImageView(item.getImage()));
setTooltip(tt);
} else {
setText(null);
setTooltip(null);
}
}
};
});
And the result:
You can also check this question about image-tooltips: How to show Image as tooltip in JavaFX?
Upvotes: 5