java fx choicebox_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);

}

}

};

}

});

标签:javafx,css,java

来源: https://codeday.me/bug/20191027/1948402.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值