Skip to content
Advertisement

Delete highlighting in JComboBox

When a JComboBox is just made and added and all the background of the selected item is just normal and white:
(ignore the enormous spacing after the text)

before

When I then open the list and hover my cursor over an item, that item get’s highlighted, all normal, nothing wrong with it.

But the problem now is that the highlighting stays once I’ve clicked on an item:

after

So my question is:
How can I make the highlighting go away?
Preferably without doing difficult with packages from the community or overloading or whatever.

If I’m right it has to be in the ‘root’ of the action listener of the combo box?
So:

public void actionPerformed(ActionEvent e)
{
    if(e.getSource() == comboBox)
    {
        // code to delete the highlighting
    }
}

Advertisement

Answer

To make it easier for people with a similar problem, here is the code for the renderer I wrote:

import java.awt.*;
import java.awt.event.*;
import javax.swing.*;

class ComboBoxRenderer extends JLabel implements ListCellRenderer
{
    private boolean colorSet;
    private Color selectionBackgroundColor;

    public ComboBoxRenderer()
    {
        setOpaque(true);
        setHorizontalAlignment(LEFT);
        setVerticalAlignment(CENTER);
        colorSet = false;
        selectionBackgroundColor = Color.red; // Have to set a color, else a compiler error will occur
    }

    public Component getListCellRendererComponent(JList list, Object value, int index, boolean isSelected, boolean cellHasFocus)
    {
        // Check if color is set (only runs the first time)
        if(!colorSet)
        {
            // Set the list' background color to original selection background of the list
            selectionBackgroundColor = list.getSelectionBackground();
            // Do this only one time since the color will change later
            colorSet = true;
        }

        // Set the list' background color to white (white will show once selection is made)
        list.setSelectionBackground(Color.white);

        // Check which item is selected
        if(isSelected)
        {
            // Set background color of the item your cursor is hovering over to the original background color
            setBackground(selectionBackgroundColor);
        }
        else
        {
            // Set background color of all other items to white
            setBackground(Color.white);
        }

        // Do nothing about the text and font to be displayed
        setText((String)value);
        setFont(list.getFont());

        return this;
    }
}

Edit: Previous code didn’t seem to work as properly, code updated and should work all fine now

User contributions licensed under: CC BY-SA
8 People found this is helpful
Advertisement