Search code examples
javaswingpopupjcombobox

Can I modify JComboBox popup background color of an existing object?


I have an existing JComboBox object. I can modify many of its properties using the internal methods. However, I could not find similar methods to customize the popup's appearance - specifically, the popup's background color. I have an existing object, so I wish to use its existing methods/properties, not to write a dedicated class. Is this possible?

Note: this question is NOT the same as the linked question above (which incorrectly states that this question already has an answer): that question asked about the selected item's bgcolor (in the combobox's editbox); I am asking about the popup box's bgcolor.


Solution

  • As eugener said, using a custom ListCellRenderer is definitely the right way to do this. You just need to create a class that extends DefaultListCellRenderer. This default renderer extends JLabel so it couldn't be easier to understand! You just need to make a call to setBackground().

    JComboBox combo = new JComboBox(new String[] { "A", "B", "C", "D" });
    combo.setRenderer(new DefaultListCellRenderer() {
        public void paint(Graphics g) {
            setBackground(Color.YELLOW);
            setForeground(Color.RED);
            super.paint(g);
        }
    });