Multipage JTable: impossible to display less items than rows

天大地大妈咪最大 提交于 2019-12-02 18:31:44

问题


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);
}

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?


回答1:


Make sure your model's getRowCount method is inline with what you want it to do. The getRowCount method should return an acceptable number for your table, so that it doesn't call getValueAt for any rows that don't exist. So, if you have no row 14, your row count shouldn't be that high.




回答2:


I think that not easy job, I suggessting to look at aephyr's code, maybe more easies way is implementing this code, but for real effect you have to lock JScrollBars, swith to NEVER




回答3:


Just pin the the value to its acceptable maximum:

realRow = Math.min(realRow, getRowCount());

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;
    }
}

Also consider BasicArrowButton.



来源:https://stackoverflow.com/questions/8389350/multipage-jtable-impossible-to-display-less-items-than-rows

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!