java jlist显示图片,带有图片和文字的JList:文字来自ArrayList< String>

i have a simple example of a JList that is getting it's data from an ArrayList but i want to show an image next to each string in the list. I have written a custom cell renderer (IconListRenderer) that is suppose to display an icon and the object side-to-side.

Here is a running sample.

//Test class showing the list in a frame

import java.awt.Color;

import java.awt.Dimension;

import java.util.ArrayList;

import java.util.HashMap;

import java.util.Map;

import javax.swing.*;

import javax.swing.border.LineBorder;

public class Test extends JFrame{

public static void main(String[] args) {

final JFileChooser chooser = new JFileChooser();

JButton button = new JButton();

button.setText("Upload");

JFrame frame = new JFrame("My Frame");

JList list = new JList();

Map icons = new HashMap();

list.setBorder(new LineBorder(Color.BLACK));

ImageIcon icon = new ImageIcon("/Images/400px-Greek_uc_sigma.png");

ArrayList arrayList = new ArrayList();

icons.put("Name", icon);

//populate the arrayList for testing

arrayList.add("Smith");

arrayList.add("John");

arrayList.add("Bob");

arrayList.add("Kim");

frame.setSize(new Dimension(400, 400));

//set the list data

list.setListData(arrayList.toArray());

final JFrame imageFrame = new JFrame();

frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

list.setCellRenderer(new IconListRenderer(icons));

frame.add(list);

frame.setVisible(true);

frame.repaint();

}

}

//IconListRenderer class

import java.awt.Component;

import java.util.Map;

import javax.swing.DefaultListCellRenderer;

import javax.swing.Icon;

import javax.swing.ImageIcon;

import javax.swing.JLabel;

import javax.swing.JList;

public class IconListRenderer

extends DefaultListCellRenderer {

private Map icons = null;

public IconListRenderer(Map icons) {

this.icons = icons;

}

@Override

public Component getListCellRendererComponent(

JList list, Object value, int index,

boolean isSelected, boolean cellHasFocus) {

// Get the renderer component from parent class

JLabel label =

(JLabel) super.getListCellRendererComponent(list,

value, index, isSelected, cellHasFocus);

// Get icon to use for the list item value

Icon icon = icons.get(value);

// Set icon to display for value

label.setIcon(icon);

return label;

}

}

The list shows currently but no image?

解决方案

It's not really surprising:

you use the JList item value as a key to get the icon from the icon map;

the icon map contains a single key: "Name"

the JList contains "Smith", "John", "Bob" and "Kim", but no "Name"

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值