Search code examples
javaswingjcombobox

JComboBox custom display after selecting item


This might be a dup - I can't find it exactly though - I'm basically simply trying to customize a JComboBox display by providing my own ListCellRenderer:

targetCombo = new JComboBox();
targetCombo .setRenderer(new BasicComboBoxRenderer(){
    public Component getListCellRendererComponent(JList list, Object value, int index,              boolean isSelected, boolean cellHasFocus){
        super.getListCellRendererComponent(list, value, index, isSelected, cellHasFocus);
        if (value != null){
            MyObj myObj = (myObj)value;
            setText(myObj.getName());
        }
        return this;
    }
});

The component properly displays the name when I expand the JComboBox list. However, on item selection, the display reverts to the toString() value of myObj.

Am I missing something?


Solution

  • Replace the use of BasicComboBoxRenderer with DefaultListCellRenderer

    public class TestComboBox04 {
    
      public static void main(String[] args) {
        new TestComboBox04();
      }
    
      public TestComboBox04() {
        EventQueue.invokeLater(new Runnable() {
          @Override
          public void run() {
            try {
              UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
            } catch (Exception ex) {
            }
    
            JComboBox targetCombo = new JComboBox();
            targetCombo.setRenderer(new DefaultListCellRenderer() {
              public Component getListCellRendererComponent(JList list, Object value, int index, boolean isSelected, boolean cellHasFocus) {
                super.getListCellRendererComponent(list, value, index, isSelected, cellHasFocus);
                if (value != null) {
                  MyObj myObj = (MyObj) value;
                  setText(myObj.getName());
                }
                return this;
              }
            });
            targetCombo.addItem(new MyObj("A"));
            targetCombo.addItem(new MyObj("B"));
            targetCombo.addItem(new MyObj("C"));
            targetCombo.addItem(new MyObj("D"));
    
            JFrame frame = new JFrame("Test");
            frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
            frame.setLayout(new GridBagLayout());
            frame.add(targetCombo);
            frame.pack();
            frame.setLocationRelativeTo(null);
            frame.setVisible(true);
    
          }
        });
      }
    
      public class MyObj {
    
        private String name;
    
        public MyObj(String name) {
          this.name = name;
        }
    
        public String getName() {
          return name;
        }
    
      }
    
    }
    

    You should never have a need to use the components from the look and feel packages, unless you are planning on creating your own look and feel.