Scrolls JTable to the selected row. - Java Swing

Java examples for Swing:JTable Scroll

Description

Scrolls JTable to the selected row.

Demo Code


//package com.java2s;
import java.awt.Point;
import java.awt.Rectangle;

import javax.swing.JTable;
import javax.swing.JViewport;

public class Main {
    /**//from ww  w .j a  v a  2  s .c  o m
     * Scrolls table to the selected row. The table must be a child of
     * JViewport.
     * 
     * Code has been taken from:
     * http://stackoverflow.com/questions/853020/jtable-scrolling-to-a-specified-row-index
     * 
     * @param table The table to scroll.
     * @param row Which row to scroll to.
     * @param column Which column to scroll to.
     */
    public static void scrollTableToCellAt(JTable table, int row, int column) {
        if (!(table.getParent() instanceof JViewport)) {
            return;
        }
        JViewport viewport = (JViewport) table.getParent();

        // This rectangle is relative to the table where the
        // northwest corner of cell (0,0) is always (0,0).
        Rectangle rect = table.getCellRect(row, column, true);

        // The location of the viewport relative to the table
        Point pt = viewport.getViewPosition();

        // Translate the cell location so that it is relative
        // to the view, assuming the northwest corner of the
        // view is (0,0)
        rect.setLocation(rect.x - pt.x, rect.y - pt.y);

        // Scroll the area into view
        viewport.scrollRectToVisible(rect);
    }
}

Related Tutorials