2010-02-09 72 views

回答

4

Chandru的答案中的例子看起來像很多代碼,所以我可以理解你爲什麼要求更簡單的解決方案。但是,如果您子類DefaultListCellRenderer很多工作都是爲您完成的,因爲此渲染器是JLabel的子類。

JList list = ... // Create JList 

// Install custom renderer. 
list.setCellRenderer(new DefaultListCellRenderer() { 
    public Component getListCellRendererComponent(JList list, Object value, int index, boolean isSelected, boolean cellHasFocus) { 

    // Request superclass to render the JLabel. 
    Component ret = super.getListCellRenderer(list, value, index, isSelected, cellHasFocus); 

    // Now conditionally override background if cell isn't selected. 
    if (!isSelected) { 
     String s = String.valueOf(value); 

     if (s.equals("Foo")) { 
     ret.setBackground(Color.RED); 
     } else { 
     ret.setBackground(Color.GREEN); 
     } 
    } 

    return ret; 
    } 
}); 
+0

謝謝我會試試這個 – Mandar 2010-02-09 13:24:58

+0

如果你願意,你可以把這個答案(和一些其他答案)upvote。 – Adamski 2010-02-09 14:56:59

1

您必須使用自定義列表單元格渲染器。例如,查看this how-to

+0

請問您能詳細說明一下嗎? – Mandar 2010-02-09 12:59:36

+0

我編輯了我的回覆。 – 2010-02-09 13:00:19

+0

感謝您的回覆。 但是有沒有更簡單的方法? 我試過每個addItem()之後的setForeground(),但它不起作用。 我不知道爲什麼。 – Mandar 2010-02-09 13:05:06

相關問題