1

我有一个JTable,其中一个列应该显示图像;我重写了执行此操作getTableCellRendererComponent的方法。DefaultTableCellRenderer但问题是,当图像不是 Null并且单元格显示它时,此方法被反复调用(就像在无限循环中调用一样)并使用 100% 的 CPU!(当图像是Null没有问题的!)。

问题是什么?

我的扩展课程是:

public class imageCellRenderer extends DefaultTableCellRenderer{

    @Override
    public void validate() {}
    @Override
    public void revalidate() {}
    @Override
    protected void firePropertyChange(String propertyName, Object oldValue, Object newValue) {}
    @Override
    public void firePropertyChange(String propertyName, boolean oldValue, boolean newValue) {}
    @Override
    public Component getTableCellRendererComponent(JTable table, Object value, boolean isSelected, boolean hasFocus, int row, int column) {
        if(isSelected) {
            this.setBackground(table.getSelectionBackground());
            this.setForeground(table.getSelectionForeground());
        }else {
            this.setBackground(table.getBackground());
            this.setForeground(table.getForeground());
        }
        this.setIcon(null);
        Image Scaled;
        ImageIcon tmp;
        System.out.println("CR");
        if(value != null){
            System.out.println("CRP");
            if(value instanceof ImageIcon){
                tmp=(ImageIcon)value;
            }else{
                tmp=new ImageIcon(value.toString());
            }
            int w=tmp.getIconWidth();
            int h=tmp.getIconHeight();
            int refW=100;
            int refH=100;
            double ratio=(double)w/(double)h;
            if(w!=refW && h!=refH){
                int nh,nw;
                double relx=(double)w/(double)refW;
                if(((double)h/relx)<refH){
                    nh = (int) Math.round(refW / ratio);
                    nw = refW;
                }else{
                    nw=(int)Math.round(refH*ratio);
                    nh=refH;
                }
                Scaled=tmp.getImage().getScaledInstance(nw, nh, Image.SCALE_SMOOTH);

                tmp=new ImageIcon(Scaled);
            }
            this.setIcon(tmp);
            table.setRowHeight(row, tmp.getIconHeight());

            this.setSize(100, tmp.getIconHeight());
            this.setHorizontalAlignment(JLabel.CENTER);
        }
        return this;
    }

}

我像这样使用它:

jTable1.getColumnModel().getColumn(2).setCellRenderer(new imageCellRenderer());
4

1 回答 1

12

去除那个

table.setRowHeight(row, tmp.getIconHeight());

从渲染器调用。此调用将调整再次触发渲染器的行高

于 2012-10-14T09:49:44.760 回答