如何在ListView javafx中放置图像

时间:2016-01-18 19:52:13

标签: java listview javafx

在我的ListView myList 中,我希望每个项目(String)旁边都有一张迷你照片。

以下是我的ListView myList 的定义方式:

ListView<String> myList = new ListView<String>();

SearchResultList.setCellFactory(new Callback<ListView<String>,ListCell<String>>() {
        @Override 
        public ListCell<String> call(ListView<String> list) {
            return new ColorRectCell();
        }
    }
);

我读过你必须指定一个单元工厂来更新列表中的每个项目。但是我不知道这一切是如何工作的,这是我指定细胞工厂的代码

static class ColorRectCell extends ListCell<String> {
   @Override
   public void updateItem(String item, boolean empty) {

            super.updateItem(item, empty);
            Image rect = new Image("huisteken.jpg");
            ImageView rec = new ImageView(rect);
            if (item != null) { 
                System.out.println("testing" + item +"######");

                setGraphic(rec);
                setContentDisplay(ContentDisplay.GRAPHIC_ONLY);
            }

    }
 }

请欢迎任何想法或提示。

1 个答案:

答案 0 :(得分:1)

我的解决方案是将Cells文本设置为null并使Graphic包含一个包含图片和文本的Hbox。所以让你的updateItem看起来像这样:

@Override
void updateItem(final String item, final boolean empty) {
    super.updateItem(item, empty);

    // if null, display nothing
    if (empty || item == null) {
        setText(null);
        setGraphic(null);
        return;
    }

    setText(null);

    Label textLabel = new Label(item + " ");

    final HBox hbox = new HBox();
    hbox.setSpacing(5);

    Label iconLabel = new Label();
    iconLabel.setGraphic(new ImageView(new Image("huisteken.jpg")));

    hbox.getChildren().addAll(iconLabel, textLabel);
    setGraphic(hbox);
}

`