我正在使用Netbeans开发我的Java应用程序,我想显示带有图标的项目列表。我使用ListCellRenderer,但它只是显示项目,而不是图标。这是我的密码
//项目类
public class Item {
private String title;
private String imagePath;
private ImageIcon image;
//getter and setter}//ItemRenderer
public class ItemRenderer extends JLabel implements ListCellRenderer{
private static final Color HIGHLIGHT_COLOR = new Color(0, 0, 128);
public ItemRenderer() {
setOpaque(true);
setIconTextGap(12);
}
public Component getListCellRendererComponent(JList list, Object value, int index, boolean isSelected, boolean cellHasFocus)
{ try
{
Item item = (Item)value;
System.out.println("hhhhhhhhhhhhhhhhhhhhhhhhh" + item.getTitle() + ";icon=" + item.getImagePath());
setText(item.getTitle());
setIcon(item.getImage());
if (isSelected)
{
setBackground(HIGHLIGHT_COLOR);
setForeground(Color.white);
}
else
{
setBackground(Color.white);
setForeground(Color.black);
}
}
catch(UnsupportedOperationException ex)
{
throw new UnsupportedOperationException("Not supported yet.");
}
return this;
}//下面是我使用ListCellRenderer的代码
public frmMain() {
initComponents();
DefaultListModel model = new DefaultListModel();
Item [] items = null;
items = new Item[5];
for(int i=0;i<5;i++)
{
items[i] = new Item();
items[i].setTitle("Item " + i);
items[i].setImagePath("pdf-gif.gif");
model.addElement(items[i]);
}
lstLeftItems.setModel(model);
lstLeftItems.setCellRenderer(new ItemRenderer());
lstLeftItems.setVisibleRowCount(5);
}注: lstLeftItems是Jlist。
请帮我解决这个问题。
发布于 2009-12-04 07:14:35
根据您提供的代码,图标为空。我看到了设置标题和imagePath的位置,但实际上没有读取图像文件来创建图标。
如果你需要更多的帮助,发布你的SSCCE,这样我们就能看到真正的问题。
发布于 2009-12-04 10:34:18
谢谢你的回答。我没有设置图像,因为我的getter方法用于image属性,这是我的代码
public ImageIcon getImage() {
if(image==null)
{
image = new ImageIcon(imagePath);
}
return image;
}所以,仅仅设置imagePath就足够了。
https://stackoverflow.com/questions/1845210
复制相似问题