import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import javax.swing.border.*;
public class Test extends JApplet {
public void init() {
Container contentPane = getContentPane();
JComboBox combo = new JComboBox(new Object[] {
new Object[] { Color.gray, "gray" },
new Object[] { Color.orange, "orange" },
new Object[] { Color.red, "red" },
new Object[] { Color.blue, "blue" },
new Object[] { Color.yellow, "yellow" },
new Object[] { Color.magenta, "magenta" },
new Object[] { Color.black, "black" },
new Object[] { Color.green, "green" },
new Object[] { Color.lightGray, "lightGray"} });
combo.setRenderer(new ColorRenderer());
contentPane.setLayout(new FlowLayout());
contentPane.add(combo);
}
}
class ColorRenderer extends JLabel implements ListCellRenderer {
private static ColorIcon icon = new ColorIcon();
private Border
redBorder = BorderFactory.createLineBorder(Color.red,2),
emptyBorder = BorderFactory.createEmptyBorder(2,2,2,2);
public Component getListCellRendererComponent(
JList list,
Object value,
int index,
boolean isSelected,
boolean cellHasFocus) {
Object[] array = (Object[])value;
icon.setColor((Color)array[0]);
setIcon(icon);
setText((String)array[1]);
if(isSelected) setBorder(redBorder);
else setBorder(emptyBorder);
return this;
}
}
class ColorIcon implements Icon {
private Color color;
private int w, h;
public ColorIcon() {
this(Color.gray, 50, 15);
}
public ColorIcon(Color color, int w, int h) {
this.color = color;
this.w = w;
this.h = h;
}
public void paintIcon(Component c, Graphics g, int x, int y) {
g.setColor(Color.black);
g.drawRect(x, y, w-1, h-1);
g.setColor(color);
g.fillRect(x+1, y+1, w-2, h-2);
}
public Color getColor() {
return color;
}
public void setColor(Color color) {
this.color = color;
}
public int getIconWidth() {
return w;
}
public int getIconHeight() {
return h;
}
}