Câu trả lời đầu tiên hoạt động tốt, nhưng hàng đã chọn được đặt ở cuối bảng. Vì vậy, tôi đã tạo phiên bản được sửa đổi này:
private void scrollToVisible(int rowIndex, int vColIndex) {
JTable table = getTablePanel().getTable();
if (!(table.getParent() instanceof JViewport)) {
return;
}
if (table.getRowCount()<1){
return;
}
JViewport viewport = (JViewport)table.getParent();
// view dimension
Dimension dim = viewport.getExtentSize();
// cell dimension
Dimension dimOne = new Dimension(0,0);
// This rectangle is relative to the table where the
// northwest corner of cell (0,0) is always (0,0).
Rectangle rect = table.getCellRect(rowIndex, vColIndex, true);
Rectangle rectOne;
if (rowIndex+1<table.getRowCount()) {
if (vColIndex+1<table.getColumnCount())
vColIndex++;
rectOne = table.getCellRect(rowIndex+1, vColIndex, true);
dimOne.width=rectOne.x-rect.x;
dimOne.height=rectOne.y-rect.y;
}
// '+ veiw dimension - cell dimension' to set first selected row on the top
rect.setLocation(rect.x+dim.width-dimOne.width, rect.y+dim.height-dimOne.height);
table.scrollRectToVisible(rect);
}
Bây giờ hàng được chọn sẽ được đặt ở đầu bảng.
Sai và quá phức tạp! Điều này có thể được thực hiện trong một dòng đơn: – Elmue
table.scrollRectToVisible (table.getCellRect (hàng, cột, true)); – Elmue