JList,JComboBox和LIstCellRenderer的爱恨情长

myLIstCellRenderer 实现:

在这里插入代码片
import java.awt.Component;

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

public class my implements ListCellRenderer {
private JLabel a=new JLabel("",JLabel.CENTER);
	@Override
	public Component getListCellRendererComponent(JList arg0, Object arg1, int arg2, boolean arg3, boolean arg4) {
		// TODO 自动生成的方法存根
		Object []a1=(Object[]) arg1;
		a.setIcon((Icon) a1[0]);
		a.setOpaque(true);
		a.setText((String) a1[1]);
		return a;
	}

}

JComboBox

在这里插入代码片
import java.awt.BorderLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.Calendar;
import java.util.Date;
import java.util.List;

import javax.swing.*;
import javax.swing.event.*;
import javax.swing.event.*;

public class Main1 extends JApplet{
	ImageIcon a1=new ImageIcon("D:\\java1\\程序\\ai\\程序\\src\\lianxi\\t.jpg");
	private DefaultComboBoxModel d=new DefaultComboBoxModel();
	private JComboBox c=new JComboBox(d);
	private my m=new my();
	public Main1() {
		d.addElement(new Object[]{a1,"asfs"});
		d.addElement(new Object[] {new ImageIcon("D:\\java1\\程序\\ai\\程序\\src\\lianxi\\a.jpg"),"dshsg"});
		c.setRenderer(m);
		add(c);}
}

注意:
这里图片的地址是小编的本地地址,当用的时候需要设置你要实现的图片的地址。利用LIstCellRenderer,JList,JComboBox可以实现每项是字体和图片的组合,JLIst和LIstCellRenderer与JComboBox和LIstCellRenderer几乎相同。

发布了141 篇原创文章 · 获赞 16 · 访问量 3万+

猜你喜欢

转载自blog.csdn.net/feiqipengcheng/article/details/105176168