1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54
|
import javax.swing.JLabel;
import javax.swing.ListCellRenderer;
import javax.swing.JList;
import java.awt.Component;
import java.awt.Dimension;
import java.awt.Color;
import java.awt.Graphics;
/**
* Created by IntelliJ IDEA.
* User: bebe
* Date: Jun 1, 2006
* Time: 7:01:53 PM
* To change this template use File | Settings | File Templates.
*/
public class MyRenderer extends JLabel implements ListCellRenderer {
/* The background color that will be used to paint the label. */
private Color backgroundColor = null;
public MyRenderer() {
/*
each color is rendered as a label. [width = 200 and height = 50].
*/
setPreferredSize(new Dimension(200, 50));
setOpaque(true);
}
/*
This is also a method called by Swing. Like in the model. When why... swing knows when ;-)
For each value of you model, for each colors, swing asks :"you how should I display this item ?"
And what you have to do is to answer his question returning him a whatever Component (jlabel, jPanel, jTextField...).
here, you return this himself because I extended JLabel, but before doing that, you need to repaint
the label using the selected color.
*/
public Component getListCellRendererComponent(JList list, Object value, int index, boolean isSelected, boolean cellHasFocus) {
if (value != null) {
backgroundColor = (Color) value;
} else {
backgroundColor = null;
}
return this;
}
/* Paint the label with the selected color. */
@Override
public void paint(Graphics g) {
setBackground(backgroundColor);
super.paint(g);
}
} |
Partager