JavaFX:带有图像和文本的ChoiceBox

我想创建一个带有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"); } 

所以我想我可以通过#accChoiceBox .menu-item:nth-of-type(1) .label或类似的方式为每个条目赋予自己的图标,但我尝试过的选择器都没有。

好的,只需使用ComboBox而不是ChoiceBox就可以解决问题(感谢James_D )。 网上有很多关于ComboBoxes中图像的例子和解决方案。 无论如何,我也会在这里留下自己的。

它只是给出ComboBox icon_1.png中的第一个条目,第二个是icon_2.png ,依此类推。

 comboBox.setCellFactory(new Callback, ListCell>() { @Override public ListCell call(ListView p) { return new ListCell() { @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); } } }; } });