We help IT Professionals succeed at work.

Change color of an item in JList

Cuong
Cuong asked
on
Medium Priority
2,186 Views
Last Modified: 2008-02-01
All,

I have a vector of Strings, and a JList will be created with this vector to display a list of all the Strings in the vector.

I want to be able to make specific strings in this JList a different color.

Can anybody tell me how this is done?

Thanks in advance
Comment
Watch Question

CERTIFIED EXPERT
Top Expert 2004
Commented:
You need to do something like this:

===============================================

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

class MyListRenderer implements ListCellRenderer
{
  JLabel renderer ;
  boolean showDesc = true ;

  public MyListRenderer()
  {
    renderer = new JLabel() ;
  }

  public Component getListCellRendererComponent( JList table,
                                                 Object value,
                                                 int row,
                                                 boolean selected,
                                                 boolean focus )
  {
    renderer.setText( value.toString ) ;
    renderer.setForeground( Color.red ) ;
    return renderer ;
  }
}

================================================

And then, you set the renderer on your list like:

  jList1.setRenderer( new MyListRenderer() ) ;

as you can see...this will make all items red.

You can change this in the renderer, or if you make your list a vector of classes (string and color), you can set the text to the string with setText() and set the color to the color :-)

If you see what I mean...

Good luck!!

Tim.

Author

Commented:
Sorry" meant to accept this answer a long time ago.

Thanks again..
CERTIFIED EXPERT
Top Expert 2004

Commented:
np :-)

Thanks :-)