Win a copy of Murach's Python Programming this week in the Jython/Python forum!
  • Post Reply Bookmark Topic Watch Topic
  • New Topic

JComboBox with muticolor items??  RSS feed

 
Sajee Joseph
Ranch Hand
Posts: 200
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi,
I have a JComboBox which displays a set of names like
"Sam","Saj","Jane"..... and so on. Now depending on some condition i need the names in the JComboBox to have different colors. I need just 2 colors.
How do i do that.
Code exampples will be helpful
Waiting for ur replies
Regards
Saj
 
john mattucci
Ranch Hand
Posts: 331
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
This answer was given to me several weeks back and it should also
answer your question
You have to write your own ListCellRenderer and a data class. That is for instance extend JLabel and implement the appropriate interface. Please take a look at the api documentation of the ListCellRenderer interface. The only to implement method is
public Component getListCellRendererComponent(...)
So you have to define your data class, for instance:
public class MyData
{
private String mDescription = "default";
public String getDescription()
{
return mDescription;
}
public void setDescription(String description)
{
mDescription = description != null ? description : "default";
}
}
and define the cell renderer:
class MyDataCellRenderer extends JLabel implements ListCellRenderer
{
public MyDataCellRenderer()
{
setOpaque(true);
}
public Component getListCellRendererComponent(JList list, Object value, int index, boolean isSelected, boolean cellHasFocus)
{
if (value instanceof MyData)
{
MyData myData = (MyData) value;
setText(myData.getDescription());
if (myData.isCompleted())
{
if (isSelected)
{
// change the colors to the desired:
setBackground(list.getSelectionBackground());
setForeground(Color.red);
}
else
{
// change the colors to the desired:
setBackground(list.getBackground());
setForeground(Color.red);
}
}
else
{
if (isSelected)
{
setBackground(list.getSelectionBackground());
setForeground(list.getSelectionForeground());
}
else
{
setBackground(list.getBackground());
setForeground(list.getForeground());
}
}
}
return this;
}
}
Finally you have to make your ListCellRenderer the cell renderer of the JList: myJList.setCellRenderer(...);
and you add elements of MyData to the JList...
You can find another example in the api documentation of JList...
Good luck
Tom

 
Don't get me started about those stupid light bulbs.
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!