Java List set列表项的背景

如何更改Java AWT List项的背景颜色?我指的是AWT列表中的单个项目,而不是整个事物。     
已邀请:
您需要一个自定义渲染器。也就是说,如果你使用的是Swing。坚持使用Swing组件而不是awt gui组件会更好。
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.
  }
}
    
由于Java AWT List继承自Component,因此使用Component的setBackground(Color c)方法。
List coloredList = new List(4, false);
Color c = new Color(Color.green);
coloredList.add("Hello World")
coloredList.setBackground(c);
列表现在有一个绿色。     
我已经和AWT合作过了一段时间,但你不能只使用setBackground(Color)吗? List是java.awt.Component的子类。     

要回复问题请先登录注册