gpt4 book ai didi

Java组合框如何添加图标?

转载 作者:塔克拉玛干 更新时间:2023-11-03 05:02:49 25 4
gpt4 key购买 nike

我是 FXML 的新手,正在构建一个应用程序。现在我遇到了一个我无法解决的问题。

我在 FXML 中定义了一个组合框,并在 Controller 类中创建了必要的关联。但我想将图像添加到此组合框。

在谷歌上搜索了几个小时后,我仍然无法解决这个问题。

你们能帮我举一个“简单”的例子来说明如何实现我的目标吗?

非常感谢!

我当前的代码是:(确保有更简单的方法来做到这一点,但它有效!)

ImageView img1 = new ImageView("Layout/nl.png");
ImageView img2 = new ImageView("Layout/en.png");

AnimalBoxLanguage.getItems().addAll(img1, img2);

AnimalBoxLanguage.setCellFactory(new Callback<ListView<ImageView>, ListCell<ImageView>>() {
@Override
public ListCell<ImageView> call(ListView<ImageView> p) {
return new ListCell<ImageView>() {
private final ImageView rectangle;
{
setContentDisplay(ContentDisplay.GRAPHIC_ONLY);
rectangle = new ImageView();
}

@Override
protected void updateItem(ImageView item, boolean empty) {
super.updateItem(item, empty);

if (item == null || empty) {
setGraphic(null);
} else {
rectangle.setImage(item.getImage());
setGraphic(rectangle);
}
}
};
}
});

最佳答案

sample erhun 在他的评论中链接作为起点,在 fxml 中定义组合框,如下所示,以便组合框项目包含带有图形的标签(这些是你的“图标”)。

<ComboBox fx:id="fruitCombo" layoutX="15.0" layoutY="33.0" prefWidth="90.0" promptText="choose">
<items>
<FXCollections fx:factory="observableArrayList">
<Label text="Apple">
<graphic>
<StackPane prefWidth="50">
<ImageView fitHeight="32" preserveRatio="true">
<image>
<Image url="http://uhallnyu.files.wordpress.com/2011/11/green-apple.jpg" preserveRatio="false" smooth="false" />
</image>
</ImageView>
</StackPane>
</graphic>
</Label>
<Label text="Pear">
<graphic>
<StackPane prefWidth="50">
<ImageView fitHeight="32" preserveRatio="true">
<image>
<Image url="http://smoothiejuicerecipes.com/pear.jpg" preserveRatio="false" smooth="false" />
</image>
</ImageView>
</StackPane>
</graphic>
</Label>
<Label text="Orange">
<graphic>
<StackPane prefWidth="50">
<ImageView fitHeight="32" preserveRatio="true">
<image>
<Image url="http://i.i.com.com/cnwk.1d/i/tim/2011/03/10/orange_iStock_000001331357X_540x405.jpg" preserveRatio="false" smooth="false" />
</image>
</ImageView>
</StackPane>
</graphic>
</Label>
</FXCollections>
</items>
</ComboBox>

然后在 FruitComboController 初始化方法中,为按钮设置一个自定义单元格(下面的简单单元格仅包含所选项目的文本,但如果您愿意,也可以包含图形):

ListCell<Label> buttonCell = new ListCell<Label>() {
@Override protected void updateItem(Label item, boolean isEmpty) {
super.updateItem(item, isEmpty);
setText(item == null ? "" : item.getText());
}
};
fruitCombo.setButtonCell(buttonCell);

以上只是实现此目的的一种方法。或者(也许最好)你可以为你的 ComboBox 定义一个单元工厂,正如塞巴斯蒂安在他的回答中指出的那样。

修改样本的输出:

iconcombosample

关于Java组合框如何添加图标?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14327275/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com