开发者

Java List set Background of list item

How does o开发者_Go百科ne change the background color of a Java AWT List item? By that I mean a single item in a AWT List, not the whole thing.


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.
  }
}


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.


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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜