tags:

views:

18

answers:

2

I have a JComboBox contains following iems

{ "select" , "one" , "two" }

i need a separate background for first item so , i have made a condition in it's renderer like

public Component getListCellRendererComponent(JList list, Object value, int index, boolean isSelected,
 boolean cellHasFocus) {

            super.getListCellRendererComponent(list, value, index, isSelected, cellHasFocus);
            if (value != null){
                Item item = (Item)value;
                setText(item.getDescription());             
            }
            if(index==-1){
                setBackground(new Color(199,209,210));
                setForeground(Color.BLACK);
            }

            return this;
        }
}

so my question is if we disable a JComboBox, i have to made -1th index of component background color to someother color

like

if(index==-1){

   setBackground(Color.RED);
}

please advice

+1  A: 

The simplest way is always the best. Since you assigning renderer to a combobox, why don't you pass the combobox into it? Just create a custom renderer that holds the reference to a combobox then use the stored reference inside of your getListCellRendererComponent method

eugener
A: 

Maybe I'm missing something here, but if a JComboBox is disabled, then that means that it cannot popup its list of items. But if it is not showing its list of items, then that means it is not using the renderer for that list. So, why do you need to get a reference to the combobox in the renderer?

Avrom
Actually renderer is used inside of the "editor" field if combobox is not editable. Here is the proof: http://www.java2s.com/Code/JavaImages/CustomComboBoxDemo.PNG
eugener