Assumes JTable is contained in a JScrollPane. - Java Swing

Java examples for Swing:JTable Scroll

Description

Assumes JTable is contained in a JScrollPane.

Demo Code

/*//from   www  .  j a va  2  s.  c o m
 *   This program is free software: you can redistribute it and/or modify
 *   it under the terms of the GNU General Public License as published by
 *   the Free Software Foundation, either version 3 of the License, or
 *   (at your option) any later version.
 *
 *   This program is distributed in the hope that it will be useful,
 *   but WITHOUT ANY WARRANTY; without even the implied warranty of
 *   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 *   GNU General Public License for more details.
 *
 *   You should have received a copy of the GNU General Public License
 *   along with this program.  If not, see <http://www.gnu.org/licenses/>.
 */
import java.awt.Component;
import java.awt.Point;
import java.awt.Rectangle;
import javax.swing.JTable;
import javax.swing.JViewport;
import javax.swing.table.JTableHeader;
import javax.swing.table.TableCellRenderer;
import javax.swing.table.TableColumn;
import javax.swing.table.TableColumnModel;
import javax.swing.table.TableModel;

public class Main{
    private final JTable jtable;
    /**
     * Assumes table is contained in a JScrollPane. Scrolls the cell (rowIndex,
     * vColIndex) so that it is visible within the viewport.
     */
    public void scrollToVisible(int row, int col) {
        scrollToVisible(getJTable(), row, col);
    }
    /**
     * Assumes table is contained in a JScrollPane. Scrolls the cell (rowIndex,
     * vColIndex) so that it is visible within the viewport.
     */
    public static void scrollToVisible(JTable table, int row, int col) {
        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, col, 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);
    }
    /**
     * returns the JTable
     */
    public JTable getJTable() {
        return jtable;
    }
}

Related Tutorials