JTable Scrolling to a Specified Row Index

前端 未结 5 1843
梦如初夏
梦如初夏 2020-12-03 00:51

I have a JTable that is within a JScrollPane. Rows are added to the table at runtime based on events that happen in my application. I want to have the scoll pan

5条回答
  •  萌比男神i
    2020-12-03 01:06

    It seems to me a lot easier to set the viewport position instead of scrolling the table. Following is my code.

    public void scrollCellToView(int rowIndex, int vColIndex) {
        if (!(this.getParent() instanceof JViewport)) {
            return;
        }
        JViewport viewport = (JViewport) this.getParent();
        Rectangle rect = this.getCellRect(rowIndex, vColIndex, true);
        Rectangle viewRect = viewport.getViewRect();
    
        int x = viewRect.x;
        int y = viewRect.y;
    
        if (rect.x >= viewRect.x && rect.x <= (viewRect.x + viewRect.width - rect.width)){
    
        } else if (rect.x < viewRect.x){
            x = rect.x;
        } else if (rect.x > (viewRect.x + viewRect.width - rect.width)) {
            x = rect.x - viewRect.width + rect.width;
        }
    
        if (rect.y >= viewRect.y && rect.y <= (viewRect.y + viewRect.height - rect.height)){
    
        } else if (rect.y < viewRect.y){
            y = rect.y;
        } else if (rect.y > (viewRect.y + viewRect.height - rect.height)){
            y = rect.y - viewRect.height + rect.height;
        }
    
        viewport.setViewPosition(new Point(x,y));
    }
    

提交回复
热议问题