62,614
社区成员
发帖
与我相关
我的任务
分享
public Dimension getPreferredSize(JComponent c) {
long width = 0;
Enumeration enumeration = table.getColumnModel().getColumns();
while (enumeration.hasMoreElements()) {
TableColumn aColumn = (TableColumn)enumeration.nextElement();
width = width + aColumn.getPreferredWidth();
}
return createTableSize(width);
}
这里可以发现,他的宽度计算,就是拿出每一列,然后累加。
而最后调用的返回值:
private Dimension createTableSize(long width) {
int height = 0;
int rowCount = table.getRowCount();
if (rowCount > 0 && table.getColumnCount() > 0) {
Rectangle r = table.getCellRect(rowCount-1, 0, true);
height = r.y + r.height;
}
// Width is always positive. The call to abs() is a workaround for
// a bug in the 1.1.6 JIT on Windows.
long tmp = Math.abs(width);
if (tmp > Integer.MAX_VALUE) {
tmp = Integer.MAX_VALUE;
}
return new Dimension((int)tmp, height);
}
这里代码主要是,计算高度,用最后一行的y加这一行的高度作为高度。然后对宽度的大小进行了限制。
public Dimension getPreferredSize() {
if (isPreferredSizeSet()) {
return super.getPreferredSize();
}
Dimension size = null;
if (ui != null) {
size = ui.getPreferredSize(this);
}
return (size != null) ? size : super.getPreferredSize();
}
先看看这几行代码:
if (isPreferredSizeSet()) {
return super.getPreferredSize();
}
if是否通过呢,isPreferredSizeSet是Component中的代码,可以发现它仅在你调用setPreferredSize的时候,而且传入一个非空的Dimension才会被设置为true。
OK。如果你没有设置这个值,那么,应该是继续往下看。
ui.getPreferredSize(this);
那这个UI指的是什么呢?
在JTable的构造方法中,我们有意外发现它调用了一个updateUI的方法。
updateUI();
那updateUI方法中,到底有什么秘密呢?我们可以看到这一行代码:
setUI((TableUI)UIManager.getUI(this));
他是从UIManager中取了一个TableUI。而UIManager中是通过组件的UIClassID和类加载器,从LookAndFeel来获取UI的。
上面所有,通俗的说就是,当你没有调用JTable的setPreferredSize时,它是通过TableUI来计算大小的。