我正在制作一个自定义的ListCellRenderer。我知道你可以为每个单独的单元格设置不同的尺寸。但是现在我想为所选单元格设置不同的维度。不知何故,JList在第一次计算每个单元格的边界时缓存每个单元格的维度。 这是我的代码:Java Swing:带有ListCellRenderer的JList所选项目不同高度
public class Test {
static class Oh extends JPanel {
public Oh() {
setPreferredSize(new Dimension(100, 20));
}
protected void paintComponent(Graphics g) {
super.paintComponent(g);
g.setColor(Color.WHITE);
g.fillRect(0, 0, getWidth(), getHeight());
}
}
static class Yeah extends JPanel {
private boolean isSelected;
public Yeah(boolean isSelected) {
setPreferredSize(new Dimension(100, 100));
this.isSelected = isSelected;
}
protected void paintComponent(Graphics g) {
super.paintComponent(g);
//setSize(100, 100); // doesn't change the bounds of the component
//setBounds(0, 0, 100, 100); // this doesn't do any good either.
if (isSelected) g.setColor(Color.GREEN);
else g.setColor(Color.BLACK);
g.fillRect(0, 0, getWidth(), getHeight());
}
}
public static void main(String[] args) {
JFrame f = new JFrame();
f.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
f.setSize(800, 500);
Vector<Integer> ints = new Vector<Integer>();
for (int i = 0; i < 100; i++) {
ints.add(i);
}
JList list = new JList(ints);
list.setCellRenderer(new ListCellRenderer() {
public Component getListCellRendererComponent(JList list, Object value, int index, boolean isSelected, boolean cellHasFocus) {
if (isSelected || ((Integer) value) == 42) return new Yeah(isSelected);
else return new Oh();
}
});
//list.setPrototypeCellValue(null);
//list.setFixedCellHeight(-1);
f.add(new JScrollPane(list));
f.setVisible(true);
}
}
在评论你可以看到我已经试过了。
我已经搜索了很长时间,发现很多无用的文章,其中一些触摸ListCellRenderer /动态高度的东西,但他们只工作,因为单个单元格的高度保持不变。我的高度正在发生变化,那么我该怎么做?
我的想法是,你以后得到OutofMemory错误,因为BasicListUI CellRendererPane缓存所有添加的组件(是和哦类)。 这个错误我得到了我的用例,最后我创建了BasicListUI的子类来删除所有以前注册的组件。 – 2013-07-03 11:11:55