为JList中的元素添加图标

swing中,为Jlist提供了默认的DefaultListCellRenderer,该类继承自Jlabel,并实现了ListCellRenderer接口,但是该render不支持图标和文字同时显示,查看其源码(摘取相关部分):

public class DefaultListCellRenderer extends JLabel
    implements ListCellRenderer, Serializable

 

 public Component getListCellRendererComponent(
        JList list,
	Object value,
        int index,
        boolean isSelected,
        boolean cellHasFocus)
    {
          if (value instanceof Icon) {
	    setIcon((Icon)value);
	    setText("");
            }else {
	    setIcon(null);
	    setText((value == null) ? "" : value.toString());
	}	
         return this;
    }

 

 要想实现既显示图标,又显示文字,我们可以继承DefaultListCellRenderer,重写里面的getListCellRendererComponent()即可,伪代码如下:

jList.setCellRenderer(new DefaultListCellRenderer(){
          private static final long serialVersionUID = 1L;
			
	@Override
	public Component getListCellRendererComponent(JList list,
		Object value, int index, boolean isSelected,
		boolean cellHasFocus) {
			setIcon(ImageIcons.key_gif);
			setText(value.toString());
				
			if (isSelected) {
				setBackground(list.getSelectionBackground());
				setForeground(list.getSelectionForeground());
			} else {
				// 设置选取与取消选取的前景与背景颜色.
				setBackground(list.getBackground());
				setForeground(list.getForeground());
			}
			return this;
		}
        });

 简单效果如下:


为JList中的元素添加图标

 

http://huangqiqing123.iteye.com/blog/1462558


 

你可能感兴趣的:(JList)