2009-07-02 8 views

Odpowiedz

14

Aby dostosować wygląd komórek JList, należy napisać własną implementację ListCellRenderer.

Implementacja próbka class może wyglądać następująco: (wstępny szkic, nie testowane)

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; 
    } 
} 

Do użycia tej renderujący, w konstruktorze twoi JList „s umieścić ten kod:

setCellRenderer(new MyListCellThing()); 

Aby zmienić zachowanie komórki na podstawie wybranych i mających fokus, należy użyć podanych wartości logicznych.

+0

Ostrożnie, musisz poradzić sobie z przypadkiem, w którym rząd jest wybrany (kolor zmienia się wtedy) –

+0

tak, wspomniałem o tym na dole postu. – jjnguy

+0

Drobne wybijanie: powinno być ustawioneBackground zamiast setBackgroundColor. – ataylor