Domanda

In Java Come faccio a ottenere un JList con i colori alternati? Ogni codice di esempio?

È stato utile?

Soluzione

Per personalizzare l'aspetto di una JList celle è necessario scrivere una propria implementazione di un 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 usare questo renderer, nel costruttore 's tuoi <=> inserire questo codice:

setCellRenderer(new MyListCellThing());

Per modificare il comportamento della cella in base selezionata e ha messa a fuoco, utilizzare i valori booleani previste.

Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top