The first answer works well, but the selected row is located at the bottom of the table. Therefore, I created this modified version:
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); }
Now the selected row will be located at the top of the table.
MGaidamak Mar 12 '13 at 11:51 2013-03-12 11:51
source share