簡體   English   中英

Java列表集列表項的背景

[英]Java List set Background of list item

如何更改Java AWT列表項的背景顏色? 我的意思是指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的子類。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM