Background color of the selected item in an uneditable JComboBox
Asked Answered
L

4

7

The background color of the selected item in an uneditable JComboBox is a sort of blue:

alt text

Is there any way to make this a different color, such as white, for example?

Lunik answered 10/12, 2010 at 20:14 Comment(1)
Related, possibly duplicate, can't decide: #10258724Caddie
T
9

This should work

jComboBox1.setRenderer(new DefaultListCellRenderer() {
    @Override
    public void paint(Graphics g) {
        setBackground(Color.WHITE);
        setForeground(Color.BLACK);
        super.paint(g);
    }
});
Taciturnity answered 10/12, 2010 at 20:30 Comment(1)
This only works, if you don't need to override the getListCellRendererComponent method of the CellRenderer. If you have to do this, use the setSelectionBackground, like it was shown in camickr's answer.Guitarfish
O
7

The background assigned by the renderer is overriden by the selection background color of the JList that is used in the popup for the combo box. Check out the "paintCurrentValue" method of the BasicComboBoxUI class. So the workaround would be:

JComboBox comboBox = new JComboBox(...);
Object child = comboBox.getAccessibleContext().getAccessibleChild(0);
BasicComboPopup popup = (BasicComboPopup)child;
JList list = popup.getList();
list.setSelectionBackground(Color.RED);

This will affect the rendering of the popup as well. If you don't want it to affect the popup then you will need to create a custom renderer to specifically set the background of selected items.

Outguess answered 10/12, 2010 at 20:25 Comment(0)
D
3

Have you tried writing your own, custom, ListCellRenderer?

When that method is asked to provide a cell-rendering component you get the following arguments:

 public Component getListCellRendererComponent(JList list,
                                               Object value,
                                               int index,
                                               boolean isSelected,
                                               boolean cellHasFocus) {
Deutzia answered 10/12, 2010 at 20:18 Comment(2)
Use the code aioob provided and just cast value to a JLabel and set its background to the color you want.Interlude
Yes, I tried that. That can change the appearance of the menu items as you see them in the drop-down box. However, it doesn't change the appearance of the selected item.Lunik
I
0

This works for me:

myComboBox.setBackground(Color.RED);
myComboBox.repaint();
Ikey answered 17/10, 2021 at 3:55 Comment(1)
Please try to give proper explanation of the answer.Disrespect

© 2022 - 2024 — McMap. All rights reserved.