美文网首页
JList设置样式ListCellRenderer

JList设置样式ListCellRenderer

作者: 开心的小哈 | 来源:发表于2021-12-01 22:58 被阅读0次
    package com.main.list;
    
    import javax.swing.*;
    import java.awt.*;
    
    public class ListCellRendererTest {
        public static void main(String [] age){
            new ListCellRendererTest().init();
        }
        public void init(){
            String imagePath[]={"1f432","1f433","1f434","1f435","1f436","1f437"};
    
            JFrame jf = new JFrame("ListCellRenderer");
            JList<String> friendsList = new JList<>(imagePath);
            //给JList设置ListCellReader
            friendsList.setCellRenderer(new MyRenderer());
            jf.add(friendsList);
            jf.pack();
            jf.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
            jf.setVisible(true);
    
    
        }
        private class MyRenderer extends JPanel implements ListCellRenderer{
            private String name;
            private ImageIcon icon;
            //记录背景色
            private Color backGround;
            //记录前景色
            private Color foreGround;
            @Override
            public Component getListCellRendererComponent(JList list, Object value, int index, boolean isSelected, boolean cellHasFocus) {
               //重置成员变量
                this.name=value.toString();
                this.icon= new ImageIcon("img\\"+name+".png");
                this.backGround=isSelected? list.getSelectionBackground():list.getBackground();
                this.foreGround=isSelected? list.getSelectionForeground():list.getForeground();
                return this;
            }
    
            @Override
            public Dimension getPreferredSize() {
                return new Dimension(60,80);
            }
    
            //绘制列表内容
            @Override
            public void paint(Graphics g) {
                int imageWidth=icon.getImage().getWidth(null);
                int imageHeight=icon.getImage().getHeight(null);
                //填充背景矩形
                g.setColor(backGround);
                g.fillRect(0,0,this.getWidth(),this.getHeight());
                //绘制头像
                g.drawImage(icon.getImage(),this.getWidth()/2-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()*10/2,10+imageHeight+20);
            }
        }
    
    }
    
    

    效果


    屏幕截图(4).png

    相关文章

      网友评论

          本文标题:JList设置样式ListCellRenderer

          本文链接:https://www.haomeiwen.com/subject/snbexrtx.html