title: Modify ComboBox display in Swing
body: <p>I want to modify the display of a (non-editable) <code>JComboBox</code> in such a fashion that the currently selected entry has some extra text in the edit field (<em>not</em> the dropdown list, though).</p>
  
  <p>Something like this:</p>
  
  <p><img src="https://i.stack.imgur.com/q3Onr.png" alt="Mockup"></p>
  
  <p>My first guess was to override the ComboBox’ model so that <code>getSelectedItem</code> returns a wrapper object modifying the display:</p>
  
  <pre><code>petList.setModel(new ComboBoxModel() {
      private Object selected;
  
      public void setSelectedItem(Object anItem) {
          selected = anItem;
      }
  
      public Object getSelectedItem() {
          return new ActiveComboItem(selected);
      }
  
      // … The rest of the methods are straightforward.
  });
  </code></pre>
  
  <p>Where <code>ActiveComboItem</code> looks as follows:</p>
  
  <pre><code>static class ActiveComboItem {
      private final Object item;
  
      public ActiveComboItem(Object item) { this.item = item; }
  
      @Override
      public boolean equals(Object other) {
          return item == null ? other == null : item.equals(other);
      }
  
      @Override
      public String toString() { return String.format("Animal: %s", item); }
  }
  </code></pre>
  
  <p>Indeed, this works as far as modifying the display goes. Unfortunately, the current entry is no longer marked as active:</p>
  
  <p><img src="https://i.stack.imgur.com/MUvwd.png" alt="Wrong display"></p>
  
  <p>(Note the missing check mark … or however the selection is displayed by your OS.)</p>
  
  <p>Further inspection shows that the model’s <code>getElementAt</code> method is called with an index of <code>-1</code> every time the user selects a new item in the box. This is <em>only</em> the case when using the modified selected item. When the model’s <code>getSelectedItem</code> method returns the plain object without wrapper, then the selected item is marked as selected in the dropdown box, and <code>getElementAt</code> is <em>not</em> called with an argument of <code>-1</code>.</p>
  
  <p>Apparently, the ComboBox is comparing each item in turn to the currently active item but, despite my overriding the <code>equals</code> method, it finds no match. <strong>How can I fix this?</strong></p>
  
  <p>(Full, compilable code for this problem <a href="https://gist.github.com/1279388" rel="nofollow noreferrer"><strong>at gist.github.com</strong></a>)</p>