简体   繁体   中英

How to put images in ListView javafx

In my ListView myList , I want each item(String) to have a mini photo next to it.

Here is my how my ListView myList is defined:

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();
        }
    }
);

I read you must specify a cell factory which updates each item in list. However I don't know how this all works, This is the code where I specify my cell factory

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);
            }

    }
 }

Please, any ideas or tips are welcome.

My solution to accomplish this is to set the Cells text to null and to make Graphic contain a Hbox containing both picture and text. So make your updateItem look like this:

@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);
}

`

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM