2009-07-02 14 views

risposta

14

Per personalizzare l'aspetto di una cella JList è necessario scrivere la propria implementazione di ListCellRenderer.

Un esempio di implementazione del class può apparire come segue: (schizzo, non testato)

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

Per utilizzare questo renderer, nel costruttore 's tuoi JList inserire questo codice:

setCellRenderer(new MyListCellThing()); 

Per modificare il comportamento della cella in base a selezionato e attivato, utilizzare i valori booleani forniti.

+0

Attento, è necessario gestire il caso in cui è selezionata la riga (cambia colore quindi) –

+0

sì, ho detto che in fondo al post. – jjnguy

+0

Minor nitpick: dovrebbe essere setBackground anziché setBackgroundColor. – ataylor

Problemi correlati