views:

45

answers:

3

Simple question: How to change a background color of a Java AWT List? By that I mean the list ITEM *not* the WHOLE list.

SO > Google

:)

+1  A: 

Since Java AWT List inherits from Component, use Component's setBackground(Color c) method.

List coloredList = new List(4, false);
Color c = new Color(Color.green);
coloredList.add("Hello World")
coloredList.setBackground(c);

List now has a color green.

Eric U.
That would do the WHOLE list. I want the background of the double-clicked list item to change not the whole list.
Dan
Add that to your question then :)
Eric U.
Yeah, now I'm trying to figure out how to set the rows of a List because new List(4,false); ain't working :P haha woo!
Dan
Well thats probably because I put the List in the EAST BorderLayout so it streches anyway... ugh! I dunno.
Dan
A: 

Been a while since I have worked with AWT, but can't you just use setBackground(Color)? List is a subclass of java.awt.Component.

northpole
+1  A: 

You'll need a custom renderer. That is, if you're using Swing. It's better to stick with the Swing components and not the awt gui components.

JList
...
setCellRenderer(new MyCellRenderer());
...
class MyCellRenderer extends DefaultListCellRenderer
{
  public Component getListCellRendererComponent(JList list, Object value, int index, boolean isSelected, boolean cellHasFocus)
  {
    super.getListCellRendererComponent(list, value, index, isSelected, cellHasFocus);
    Color bg = <calculated color based on value>;
    setBackground(bg);
    setOpaque(true); // otherwise, it's transparent
    return this;  // DefaultListCellRenderer derived from JLabel, DefaultListCellRenderer.getListCellRendererComponent returns this as well.
  }
}
Mike