主题:[讨论]请教JList问题
xw287897338
[专家分:0] 发布于 2008-07-23 16:36:00
如何让JList的每个元素既包括图片,也包含字符串,就像QQ那个样子??
回复列表 (共3个回复)
沙发
daifei4321 [专家分:2590] 发布于 2008-07-27 01:05:00
1.使用JList的setCellRenderer方法。在CellRenderer里,制造既包括图片,也包含字符串的Component.
2.去学习完整的SWING教程或者至少要学完JLIST教程。
板凳
daifei4321 [专家分:2590] 发布于 2008-07-27 01:19:00
我试验着写了一个方法,成功了的。
public static void JComplexList() {
class ImageAndText {
private BufferedImage image = new BufferedImage(24, 24, BufferedImage.TYPE_INT_RGB);
private Icon icon = new ImageIcon(image);
private String text;
private ImageAndText(Color color, String text) {
Graphics g = image.getGraphics();
g.setColor(color);
g.fillRect(0, 0, image.getWidth(), image.getHeight());
this.text = text;
}
public Icon getIcon() {
return icon;
}
public String getText() {
return text;
}
}
Vector<ImageAndText> toDisplay = new Vector<ImageAndText>();
for (int i = 0, max = 10; i < max; i++) {
toDisplay.add(new ImageAndText(new Color(255 * i / max, 127, 0), "Color " + i));
}
JList list = new JList(toDisplay);
class MyRenderer extends JPanel implements ListCellRenderer {
private static final long serialVersionUID = 1L;
JLabel left = new JLabel();
JLabel right = new JLabel();
public MyRenderer() {
super.setLayout(new BorderLayout());
add(left, BorderLayout.WEST);
add(right, BorderLayout.CENTER);
setBorder(BorderFactory.createRaisedBevelBorder());
}
@Override
public Component getListCellRendererComponent(JList list,
Object value, int index, boolean isSelected,
boolean cellHasFocus) {
ImageAndText thing = (ImageAndText) value;
left.setIcon(thing.getIcon());
right.setText(thing.getText());
return this;
}
}
list.setCellRenderer(new MyRenderer());
JFrame f = new JFrame();
f.add(list);
f.pack();
f.setLocationRelativeTo(null);
f.setVisible(true);
}
我来回复