使用ListRenderer改变外观列表,写好友列表

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);
        }
    }
}

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值