现在的位置: 首页 > java > j2se > 正文
jlist设置单元格的高度
2012年08月02日 j2se ⁄ 共 2077字 暂无评论

因为JList的cellHeight默认每个cell的大小都相等,给你提供一个解决这个问题的思路:修改ListUI,其中有个参数cellHeights,可以设置每行的高度。
这不是一个完美的解决方案,不过可以参考这个思路进一步完善。如果你有更好的办法,请告诉我:)

import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Component;
import javax.swing.DefaultListCellRenderer;

import javax.swing.DefaultListModel;
import javax.swing.JFrame;
import javax.swing.JList;
import javax.swing.border.LineBorder;
import javax.swing.plaf.basic.BasicListUI;

/**
* @author sunsnowad
*
*/
public class Main {

    public static void main(String[] args) {
        Main m = new Main();

    }

    public Main() {
        JFrame f = new JFrame();
        f.setLayout(new BorderLayout());
        f.setSize(400, 800);
        JList l = new JList();
        DefaultListModel model = new DefaultListModel();
        model.addElement("1");
        model.addElement("2");
        l.setModel(model);
        CustomerUI ui = new CustomerUI();

        l.setUI(ui);

        l.setCellRenderer(new DefaultListCellRenderer() {

            @Override
            public Component getListCellRendererComponent(JList list, Object value,
                    int index, boolean isSelected, boolean cellHasFocus) {
                if (isSelected) {
                    this.setIcon(XX);
                    this.setBorder(new LineBorder(Color.yellow));
                    ((CustomerUI) list.getUI()).setCellHeight(index, 40, 20);
                    //TODO 添加图片
                    return this;
                } else {
                    this.setIcon(XX);
                    this.setBorder(new LineBorder(Color.yellow));
                    ((CustomerUI) list.getUI()).setCellHeight(index, 20);
                    this.setOpaque(true);
                    return this;
                }
            }
        });

        f.add(l);
        f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        f.setVisible(true);
    }
}

class CustomerUI extends BasicListUI {

    public CustomerUI() {
        super();
        cellHeights = new int[2];
    }

    public void setCellHeight(int index, int value, int defaultHeight) {
        for (int i = 0; i < cellHeights.length; i++) {
            cellHeights[i] = defaultHeight;
        }
        cellHeights[index] = value;
    }

    void setCellHeight(int index, int i) {
        cellHeights[index] = i;
    }
}

给我留言

您必须 [ 登录 ] 才能发表留言!

×