创建头像下拉列表

 
HashMap<String,ImageIcon>  getIcons()
	{
		//返回一个Map, key是文件的路径
	
		File folder = new File("images/heads");
	    File[] files = folder.listFiles();
		HashMap<String, ImageIcon> heads = new HashMap<String, ImageIcon>();
		for (int i = 0; i < files.length; i++) {
			File file = files[i];
			heads.put(file.getPath(), new ImageIcon(file.getAbsolutePath()));
		}
		return heads;
	}



this.headSelect = new JComboBox(this.heads.keySet().toArray());
		this.headSelect.setMaximumRowCount(5);
		this.headSelect.setRenderer(new HeadComboBoxRenderer(this.heads));
然后添加
HeadComboBoxRenderer类
import java.awt.Component;
import java.util.HashMap;
import java.util.Map;

import javax.swing.Icon;
import javax.swing.ImageIcon;
import javax.swing.JLabel;
import javax.swing.JList;
import javax.swing.ListCellRenderer;


public class HeadComboBoxRenderer extends JLabel implements ListCellRenderer {

	private Map<String, ImageIcon> heads;
	
	public HeadComboBoxRenderer(HashMap<String, ImageIcon> heads)
	{
		this.heads=heads;
		setOpaque(true);
        setHorizontalAlignment(CENTER);
        setVerticalAlignment(CENTER);
	}

	public Component getListCellRendererComponent(JList list, Object value,
			int index, boolean isSelected, boolean cellHasFocus) {
	    String selectValue = (String)value;
        //设置背景颜色
        if (isSelected) {
            setBackground(list.getSelectionBackground());
            setForeground(list.getSelectionForeground());
        } else {
            setBackground(list.getBackground());
            setForeground(list.getForeground());
        }
        //从头像的Map中得到当前选择的头像图片
        Icon icon = this.heads.get(selectValue);
        setIcon(icon);
        if (icon != null) setFont(list.getFont());
        return this;
	}

}




   

你可能感兴趣的:(创建头像下拉列表)