JComboBox每個Item加圖標

import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import javax.swing.event.*;

public class JComboBoxDemo3 {
	
	String[] s = {"西瓜","蘋果","草莓","香蕉"};
	public JComboBoxDemo3(){
		JFrame jf = new JFrame();
		Container contentPane = jf.getContentPane();
		
		JComboBox combo = new JComboBox(s);
		combo.setBorder(BorderFactory.createTitledBorder("你喜歡什么?"));
		combo.setRenderer(new ACellRenderer());
		//combo.setMaximumRowCount(2);
		
		contentPane.add(combo);
		jf.pack();
		jf.setVisible(true);
		jf.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
	}
	
	public static void main(String...args){
		new JComboBoxDemo3();
	}
	
	class ACellRenderer extends JLabel implements ListCellRenderer{
		
		ACellRenderer(){
			setOpaque(true);
		}

		@Override
		public Component getListCellRendererComponent(JList list, Object value,
				int index, boolean isSelected, boolean cellHasFocus) {
			if(value!=null){
				setText(value.toString());
				setIcon(new ImageIcon(".\\Icons\\home.jpg"));
			}
			if(isSelected){
				setBackground(list.getSelectionBackground());
				setForeground(list.getSelectionForeground());
			}
			else{
				setBackground(list.getBackground());
				setForeground(list.getForeground());
			}
			return this;
		}
	}
}


摘自:深入淺出Java Swing程序設計

你可能感兴趣的:(java,swing)