JavaFX ComboBox 图片

4

我正在尝试创建一个ComboBox,它将显示所选Image的预览,但是ComboBox显示的是字符串值。

唯一似乎有效的方法是创建NodeComboBox,但是这会导致一旦选择了选项,该选项就会从下拉菜单中消失。 如有建议,敬请赐教。

我的代码如下:

String notOnLine = "file:Java1.png";
String onLine = "file:Java2.png";
ObservableList<String> options = FXCollections.observableArrayList();
options.addAll(notOnLine, onLine);
final ComboBox<String> comboBox = new ComboBox(options);
comboBox.setCellFactory(c -> new StatusListCell());

而且还有ListCell:

public class StatusListCell extends ListCell<String> {
    protected void updateItem(String item, boolean empty){
        super.updateItem(item, empty);
        setGraphic(null);
        setText(null);
        if(item!=null){
            ImageView imageView = new ImageView(new Image(item));
            imageView.setFitWidth(40);
            imageView.setFitHeight(40);
            setGraphic(imageView);
            setText("a");
        }
    }

}

preview

当下拉列表关闭后,我希望图像能够在ComboBox本身中显示。目前它只显示URL(例如file:Java1.png)。


一旦选择了图像,我希望在组合框中看到该图像,而不仅仅是图像路径(字符串)。 - geef
1个回答

5

您可以指定ComboBoxbuttonCellProperty

comboBox.setButtonCell(new StatusListCell());

按钮电池用于显示在ComboBox“按钮”区域中显示的内容。

1
还要调整高度约束以使“ImageView”适合于“ComboBox”:comboBox.setMinHeight(50);。此外,应避免重新创建“ImageView”。将“image”属性设置为“null”应导致不显示任何内容,并允许您避免重新创建节点。对于小图像,这可能不是问题,但对于较大的图像,我建议使用缓存(例如Map<String, WeakReference<Image>>)并在后台加载图像... - fabian

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接