Uploaded image for project: 'JDK'
  1. JDK
  2. JDK-8145588

Custom rendering for selected ComboBox list item fails

XMLWordPrintable

    • x86
    • windows_7

      In the test below the selected list item should appear together with a green marker. It works well for the initially selected item. However, it looks like #updateItem() isn't called when another item is selected which seems to be the reason of why the marker isn't updated properly.

      see also http://stackoverflow.com/questions/34316254/javafx-rendering-selected-combobox-list-item

      public class ComboBoxCellFactoryTest extends Application
      {
        public static void main(String[] args)
        {
          Application.launch(args);
        }

        @Override
        public void start(Stage stage)
        {
          Parent content = createContent();
          Scene scene = new Scene(content, 400, 300);
          stage.setScene(scene);
          stage.show();
        }

        public Parent createContent()
        {
          FlowPane content = new FlowPane(10, 10);

          ComboBox<String> combo = new ComboBox<String>();
          combo.setItems(FXCollections.observableArrayList("Item 1", "Item 2", "Item 3", "Item 4"));
          combo.getSelectionModel().selectLast();
          combo.setCellFactory(new Callback<ListView<String>, ListCell<String>>()
          {
            @Override
            public ListCell<String> call(ListView<String> p)
            {
              return new ListCell<String>()
              {
                private final Rectangle rectangle;
                {
                  rectangle = new Rectangle(10, 10);
                }

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

                  if (empty || item == null)
                  {
                    setText(null);
                    setGraphic(null);
                  }
                  else
                  {
                    boolean selected = combo.getValue().equals(item);
                    rectangle.setFill(selected ? Color.GREENYELLOW : Color.RED);
                    setGraphic(rectangle);
                    setText(item);
                  }
                }
              };
            }
          });
          content.getChildren().add(combo);
          return content;
        }
      }

            jgiles Jonathan Giles
            wzberger Wolfgang Zitzelsberger
            Votes:
            1 Vote for this issue
            Watchers:
            5 Start watching this issue

              Created:
              Updated:
              Resolved: