2010-07-17 44 views
0

如何更改Java AWT列表項的背景顏色?我的意思是AWT列表中的單個項目,而不是整個項目。Java列表設置列表項的背景

+1

但Javadoc> SO! – 2010-07-17 03:03:02

+1

謝謝,但我已經看過了,而且我正在試圖跳過一棟建築物的短小男人的無奈:( – nn2 2010-07-17 03:06:27

+2

你需要學會不要這麼「無奈」。要麼你或者你需要遠離軟件開發 – 2010-07-17 03:35:36

回答

5

您將需要一個自定義渲染器。也就是說,如果你正在使用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. 
    } 
} 
0

由於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); 

列表現在有綠色。

+0

那會做整個列表。我想要雙擊列表項目的背景來更改不是整個列表。 – nn2 2010-07-17 02:53:56

+2

加上你的問題然後:) – Eric 2010-07-17 02:55:57

+0

是的,現在我想弄清楚如何設置一個列表的行,因爲新列表(4,假);不工作:P哈哈嗚! – nn2 2010-07-17 03:05:44

-1

過了一段時間,因爲我曾與AWT工作過,但不能只使用setBackground(Color)? List是java.awt.Component的一個子類。

+0

自問題編輯以來不再是正確的答案。 – 2013-03-20 10:46:38