解决方案
jtable.getHeight 不包含标题元素
jtable.getRowHeight 包含边距
示例的实际高度为 15px,而不是 14px
更清晰的示例
RO 16
R1 16
R2 16
HEIGHT 48
INTERCELL java.awt.Dimension[width=1,height=1]
MARGIN 1
我有 3 行的 JTable。每行16px。每行边距 1px。 所以我怀疑 table 高度应该是16 + 1 + 16 + 1 + 16 = 50px
但是 getHeight 返回 48px
我也做了截图。每行实际上有 14px 高度。
这怎么可能???
//headers for the table
String[] columns = new String[] {
"Id", "Name", "Hourly Rate", "Part Time"
};
//actual data for the table in a 2d array
Object[][] data = new Object[][] {
{1, "John", 40.0, false },
{2, "Rambo", 70.0, false },
{3, "Zorro", 60.0, true },
};
//create table with data
JTable table = new JTable(data, columns);
//add the table to the frame
this.add(table);
this.setTitle("Table Example");
this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
this.pack();
this.setVisible(true);
System.out.println("RO " + table.getRowHeight(0));
System.out.println("R1 " + table.getRowHeight(1));
System.out.println("R2 " + table.getRowHeight(2));
System.out.println("HEIGHT " + table.getHeight());
System.out.println("INTERCELL " + table.getIntercellSpacing());
System.out.println("MARGIN " + table.getRowMargin());
}
原始问题
我有一个简单的测试框架,滚动 Pane 中带有 jtable。
表格最小高度小于实际高度。 标题+行<实际大小
纯属无稽之谈。
val jtable = view.tableControl
val headerHeight = jtable.getTableHeader.getHeight
val rowsHeight = (0 until jtable.getRowCount()).foldLeft(0) { (heightAccumulator, counter) ⇒
println("Row " + counter + " height " + jtable.getRowHeight(counter))
jtable.getRowHeight(counter) + heightAccumulator
}
val rowsMargin = jtable.getRowMargin() * (jtable.getRowCount() - 1)
println("Actual height " + jtable.getHeight())
println("Header height " + headerHeight)
println("Margin height " + jtable.getRowMargin())
println("PreferredScrollableViewportSize" + jtable.getPreferredScrollableViewportSize())
println("Rows height " + rowsHeight)
println("Should be at least: " + (rowsHeight + headerHeight + rowsMargin))
我得到了
Row 0 height 16
Row 1 height 16
Row 2 height 16
Row 3 height 16
Row 4 height 16
Actual height 80
Header height 19
Margin height 1
PreferredScrollableViewportSizejava.awt.Dimension[width=450,height=400]
Rows height 80
Should be at least: 103
JTable 位于框架内,没有任何滚动条。它完全可见,并且下面有很大的空间。
如何?完全可见的表的jtable.getHeight()
如何返回小于 (rows * rowHeight + header) 的高度?
最佳答案
How? How jtable.getHeight() of fully visible table may returns height less then (rows * rowHeight + header)?
JTable 有一个默认的首选大小,该大小在创建表时被硬编码,因为表通常会添加到 JScrollPane 的视口(viewport)中。正如您所看到的,首选视口(viewport)尺寸要大得多,您需要一个小 table 来占用额外的空间。
如果您有一个小表格,并且希望它以最小尺寸完全显示,那么您可以使用如下代码:
JTable table = new JTable(...);
table.setPreferredScrollableViewportSize(table.getPreferredSize());
JScrollPane scrollPane = new JScrollPane( table );
关于java - J工作台高度计算,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34135994/