package itheima010; import javax.swing.*; import java.awt.*; public class ListCellRenderderDemo { public static void main(String[] args) { new ListCellRenderderDemo().init(); } String[] name = {"李清照", "何猷君", "王宪林"}; JFrame jf = new JFrame(); JList<String> jList = new JList<>(name); private void init() { // jList.setFixedCellWidth(260); // jList.setFixedCellHeight(280); jList.setCellRenderer(new myrennderer()); jf.add(jList); jf.pack(); jf.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); jf.setVisible(true); } private class myrennderer extends Panel implements ListCellRenderer{ Color background; Color foreground; ImageIcon image; String name; @Override public Component getListCellRendererComponent(JList list, Object value, int index, boolean isSelected, boolean cellHasFocus) { this.name=value.toString(); this.image=new ImageIcon("myawt\\img\\"+name+".jpg"); this.background=isSelected?jList.getSelectionBackground():jList.getBackground(); this.foreground=isSelected?jList.getSelectionForeground():jList.getForeground(); return this; } @Override public Dimension getPreferredSize() { return new Dimension(300,300); } @Override public void paint(Graphics g) { //图片宽度和高度 int imageWidth=image.getImage().getWidth(null); int imageHeight=image.getImage().getHeight(null); g.setColor(background); g.fillRect(0,0,this.getWidth(),this.getHeight()); //绘制图片 g.drawImage(image.getImage(),(this.getWidth()-imageWidth)/2,10,null); //绘制昵称 g.setColor(foreground); g.setFont(new Font("StSong",Font.BOLD,18)); g.drawString(this.name,this.getWidth()/2-this.name.length()*20/2,imageHeight+30); } } }