我想创建一个带有 JavaFX ChoiceBox 的下拉菜单,其中每个条目都包含一个不同的图标,旁边有一个短文本。(例如,在语言选择器中,左侧有一个小标志,右侧有语言名称。)
做这个的最好方式是什么?
我试图通过 CSS 来做到这一点。以下几乎有效,但当然它会为所有条目设置相同的图标:
#accChoiceBox .menu-item .label {
-fx-padding: 0 0 0 30px;
-fx-background-size: 20px 20px;
-fx-background-repeat: no-repeat;
-fx-background-image: url("../resources/images/icon.png");
}
Run Code Online (Sandbox Code Playgroud)
所以我想我可以通过#accChoiceBox .menu-item:nth-of-type(1) .label或类似的方式为每个条目提供自己的图标,但我尝试过的选择器都不起作用。
好的,通过简单地使用 ComboBox 而不是 ChoiceBox 解决了这个问题(谢谢,James_D)。网络上有很多关于 ComboBox 图像的示例和解决方案。不管怎样,我也会把我自己的留在这里。
它只会给出 ComboBoxicon_1.png中的第一个条目,第二个条目icon_2.png,依此类推。
comboBox.setCellFactory(new Callback<ListView<String>, ListCell<String>>() {
@Override
public ListCell<String> call(ListView<String> p) {
return new ListCell<String>() {
@Override
protected void updateItem(String item, boolean empty) {
super.updateItem(item, empty);
setText(item);
if (item == null || empty) {
setGraphic(null);
} else {
Image icon;
try {
int iconNumber = this.getIndex() + 1;
String iconPath = "MyProject/resources/images/icon_" + iconNumber + ".png";
icon = new Image(getClass().getClassLoader().getResourceAsStream(iconPath));
} catch(NullPointerException ex) {
// in case the above image doesn't exist, use a default one
String iconPath = "MyProject/resources/images/icon_na.png";
icon = new Image(getClass().getClassLoader().getResourceAsStream(iconPath));
}
ImageView iconImageView = new ImageView(icon);
iconImageView.setFitHeight(30);
iconImageView.setPreserveRatio(true);
setGraphic(iconImageView);
}
}
};
}
});
Run Code Online (Sandbox Code Playgroud)