JComboBox的item可不可以是图像

fios 2002-06-05 04:27:03
还有可不可以加入scrollbar


如果不能是图像,如何实现类似功能
...全文
35 5 打赏 收藏 转发到动态 举报
写回复
用AI写文章
5 条回复
切换为时间正序
请发表友善的回复…
发表回复
fightboy 2002-06-05
  • 打赏
  • 举报
回复

copy一段代码给你

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;
}
}
fat_how 2002-06-05
  • 打赏
  • 举报
回复
请问:能讲的详细一点吗?
我不是太熟!
Doctor11971 2002-06-05
  • 打赏
  • 举报
回复
I agree with Apocalypse(逍遥思辨).and
note:JComboBox.setRender(r);//r is the render you defined
马行空牛耕田 2002-06-05
  • 打赏
  • 举报
回复
呵呵
Apocalypse 2002-06-05
  • 打赏
  • 举报
回复
扩展一个DefaultListCellRenderer,重写getListCellRendererComponent()方法,其实就是在里面加一句setIcon(imageicon)

62,612

社区成员

发帖
与我相关
我的任务
社区描述
Java 2 Standard Edition
社区管理员
  • Java SE
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
暂无公告

试试用AI创作助手写篇文章吧