一遍又一遍地调用getTableCellRendererComponent并使CPU使用率达到100%

时间:2012-10-14 09:22:41

标签: java swing jtable cpu-usage tablecellrenderer

我有JTable,其中一列应显示图像; 我强调getTableCellRendererComponent DefaultTableCellRenderer方法来执行此操作。 但问题是图像 Null&单元格正在显示它这个方法被称为& amp;结束(就像它在无限循环中调用)并使用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());

1 个答案:

答案 0 :(得分:12)

删除

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

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