多页JTable:不能显示比行少的项目 [英] Multipage JTable: impossible to display less items than rows
问题描述
我实现了一个带有自定义 AbstractTableModel
的JTable来实现分页。
我想在每页显示5个项目,但我有一个问题:如果我有N项显示(N是5的倍数)一切都没关系,但是如果我,例如,有14个元素显示,我得到一个例外。问题是获取每个单元格值的方法超出了界限。特别是问题在于方法
I realized a JTable with a custom AbstractTableModel
for implementing paging.
I wanna show 5 item per page, but I've a problem: if I have N item to show (with N which is a multiple of 5) everything it's ok, but if I, for example, have 14 element to show, I get an exception. The problem is that the method for getting each cell value, goes out of bound. In particular the problem is in method
public Object getValueAt(int row, int col) {
int realRow = row + (pageOffset * pageSize);
return data[realRow].getValueAt(col);
}
实际上,我们有5行(从0到4)和14个元素,但显然当我们尝试获取最后一个元素时,我们这样做: realRow = 4 +(2 * 5)
并且显然我在第14行没有元素。
我该如何解决这个问题?如何在达到第14个文件后告诉我的程序停止获取值?有可能吗?
in fact, we have 5 row (from 0 to 4) and 14 element, but obviously when we try to obtain the last element, we do: realRow = 4 + (2*5)
and clearly I have no element at row 14.
How can I solve this problem? How can I tell to my program to stop getting value once reached the 14th file? Is it possible?
推荐答案
只需将该值固定为可接受的最大值:
Just pin the the value to its acceptable maximum:
realRow = Math.min(realRow, getRowCount());
附录:在示例引用,实现 getValueAt()
,如下所示:
Addendum: In the example cited, implement getValueAt()
as follows:
// Work only on the visible part of the table.
public Object getValueAt(int row, int col) {
int realRow = row + (pageOffset * pageSize);
if (realRow < data.length) {
return data[realRow].getValueAt(col);
} else {
return null;
}
}
还要考虑 BasicArrowButton
。
Also consider BasicArrowButton
.
这篇关于多页JTable:不能显示比行少的项目的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!