问题
I have a JTable
and one of its columns should display an image;
I overrided getTableCellRendererComponent
method of DefaultTableCellRenderer
to do this.
But the problem is while the image is not Null
& cell is displaying it this method is called over & over (like it is called in an infinite loop) and uses 100% of CPU! (When the image is Null
there is no problem!).
What is the problem?
My extended class is:
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;
}
}
and I use it like this:
jTable1.getColumnModel().getColumn(2).setCellRenderer(new imageCellRenderer());
回答1:
Remove the
table.setRowHeight(row, tmp.getIconHeight());
call from the renderer. This call will adjust the row height which triggers the renderer again
来源:https://stackoverflow.com/questions/12880867/gettablecellrenderercomponent-is-called-over-and-over-and-makes-100-cpu-usage