aspose file tools*
The moose likes Swing / AWT / SWT and the fly likes 2 colours for items in JLIST Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login
JavaRanch » Java Forums » Java » Swing / AWT / SWT
Bookmark "2 colours for items in JLIST" Watch "2 colours for items in JLIST" New topic
Author

2 colours for items in JLIST

john mattucci
Ranch Hand

Joined: Nov 03, 2000
Posts: 331
is it possible to have 2 different colours for items
in a jlist lets say completed items would be shown in
black and outstanding in red
Thank u
Thomas Suer
Ranch Hand

Joined: Sep 03, 2001
Posts: 50
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
<code>public Component getListCellRendererComponent(...)</code>
So you have to define your data class, for instance:
<code>public class MyData
{
private String mDescription = "default";
public String getDescription()
{
return mDescription;
}
public void setDescription(String description)
{
mDescription = description != null ? description : "default";
}
}</code>
and define the cell renderer:
<code>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;
}
}</code>
Finally you have to make your ListCellRenderer the cell renderer of the JList: <code>myJList.setCellRenderer(...);</code>
and you add elements of MyData to the JList...
You can find another example in the api documentation of JList...
Good luck
Tom

[This message has been edited by Thomas Suer (edited October 17, 2001).]
 
I agree. Here's the link: http://aspose.com/file-tools
 
subject: 2 colours for items in JLIST