Paul Reiners
Paul Reiners

Reputation: 7894

Background color of the selected item in an uneditable JComboBox

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?

Upvotes: 7

Views: 13186

Answers (4)

IT-Rafa
IT-Rafa

Reputation: 21

This works for me:

myComboBox.setBackground(Color.RED);
myComboBox.repaint();

Upvotes: 0

camickr
camickr

Reputation: 324118

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.

Upvotes: 7

Costis Aivalis
Costis Aivalis

Reputation: 13728

This should work

jComboBox1.setRenderer(new DefaultListCellRenderer() {
    @Override
    public void paint(Graphics g) {
        setBackground(Color.WHITE);
        setForeground(Color.BLACK);
        super.paint(g);
    }
});

Upvotes: 9

aioobe
aioobe

Reputation: 421010

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) {

Upvotes: 3

Related Questions