当组件不在可视范围(已经渲染完成)时,getHeight() 返回0
如下图:
上图中值为"registerEasemob"那行被挡住了,那么获取其中组件的getHeight()将返回0
而getPreferredSize() 则不会返回0,而是真实的高度.
所以当根据子组件高度,来调整父组件高度时,推荐使用getPreferredSize().
实例:
public void resetTableRowHeight() {
int rowCount= parameterTable_1.getRowCount();
for (int i = 0; i < rowCount; i++) {
Object cellVal= parameterTable_1.getValueAt(i,0);
JTextComponent textComponent = getCellTextComponent(cellVal);
System.out.println(" :" +textComponent.getText());
int height=textComponent.getPreferredSize().height;
cellVal= parameterTable_1.getValueAt(i,1);
JTextComponent textComponent2 = getCellTextComponent(cellVal);
int height2=textComponent2.getPreferredSize().height;
System.out.println("height2 :" +height2);
//以height为准
if(height2>height){
height=height2;
}
if(height>20) {
parameterTable_1.setRowHeight(i, height/*parameterTable_1.getRowHeight(i)*/+5);
}
}
}