Hey, noch einer der mit JavaFX arbeitet (Y)
Dein Vorhaben ist eigentlich ganz einfach. Dafür brauchst du eine überarbeitete ListCell. Leider kann man in einer ChoiceBox die CellFactory nicht setzen, deshalb habe ich jetzt ein Beispiel mit einer ComboBox gemacht.
Zuerst habe ich mir die Enum "Language" angelegt. Und da wir in Java vollwertige Klassen als Enums haben, können wir hier auch ein wenig Funktionialität mit reinbringen.
package application;
import javafx.beans.property.ReadOnlyObjectProperty;
import javafx.beans.property.ReadOnlyObjectWrapper;
import javafx.beans.property.ReadOnlyStringProperty;
import javafx.beans.property.ReadOnlyStringWrapper;
import javafx.scene.image.Image;
public enum Language
{
GERMAN("Deutsch", "german.png"),
ENGLISH("Englisch", "english.png");
private final ReadOnlyStringWrapper name;
private final ReadOnlyObjectWrapper<Image> image;
private Language(String name, String image)
{
this.name = new ReadOnlyStringWrapper(name);
this.image = new ReadOnlyObjectWrapper<>(
new Image(getClass().getResourceAsStream(image))
);
}
public ReadOnlyStringProperty nameProperty()
{
return this.name.getReadOnlyProperty();
}
public ReadOnlyObjectProperty<Image> imageProperty()
{
return this.image.getReadOnlyProperty();
}
}
Anschließend können wir die eigene ListCell erstellen.
package application;
import javafx.geometry.Pos;
import javafx.scene.control.Label;
import javafx.scene.control.ListCell;
import javafx.scene.image.ImageView;
import javafx.scene.layout.HBox;
import javafx.scene.paint.Color;
public class LanguageListCell extends ListCell<Language>
{
private final HBox graphic;
private final ImageView image;
private final Label text;
public LanguageListCell()
{
this(false);
}
public LanguageListCell(boolean useBlackText)
{
super();
this.graphic = new HBox(5.0);
this.image = new ImageView();
this.text = new Label();
if (useBlackText)
{
this.text.setTextFill(Color.BLACK);
}
this.graphic.setAlignment(Pos.CENTER_LEFT);
this.graphic.getChildren().setAll(this.image, this.text);
}
@Override
protected void updateItem(Language language, boolean empty)
{
super.updateItem(language, empty);
if (!empty && language != null)
{
this.image.imageProperty().bind(language.imageProperty());
this.text.textProperty().bind(language.nameProperty());
setGraphic(this.graphic);
}
else
{
this.image.imageProperty().unbind();
this.text.textProperty().unbind();
setGraphic(null);
}
}
}
Und zum Schluss wie man das ganze in eine ComboBox zieht:
ComboBox<Language> cb = new ComboBox<>();
cb.setCellFactory((param) -> new LanguageListCell());
cb.setButtonCell(new LanguageListCell(true));
cb.getItems().setAll(Language.values());
Ich hoffe du siehst das noch. Probier einfach mal ein bischen damit rum. Mit den CellFactories usw. kann man echt vieles in JavaFX machen.