2009-07-02 16 views

cevap

14

Bir JList hücresinin görünümünü özelleştirmek için, bir ListCellRenderer kendi uygulamanızı yazmanız gerekir.

class numunesi uygulama aşağıdaki gibi görünebilir: (test edilmedi kaba taslak,)

public class MyListCellThing extends JLabel implements ListCellRenderer { 

    public MyListCellThing() { 
     setOpaque(true); 
    } 

    public Component getListCellRendererComponent(JList list, Object value, int index, boolean isSelected, boolean cellHasFocus) { 
     // Assumes the stuff in the list has a pretty toString 
     setText(value.toString()); 

     // based on the index you set the color. This produces the every other effect. 
     if (index % 2 == 0) setBackground(Color.RED); 
     else setBackground(Color.BLUE); 

     return this; 
    } 
} 

Bu renderer kullanmak için, bu kodu koymak senin JList 'ın yapıcı içinde:

setCellRenderer(new MyListCellThing()); 

Seçili olan ve odaklanmış olan hücrenin davranışını değiştirmek için sağlanan boolean değerlerini kullanın.

+0

Dikkatli olun, satırın seçildiği durumda (renk değişiyorsa) ekranı ele almalısınız –

+0

Evet, postanın altından bahsetmiştim. – jjnguy

+0

Küçük nitpick: setBackgroundColor yerine setBackground olmalıdır. – ataylor

İlgili konular