select And Scroll JTable - Java Swing

Java examples for Swing:JTable Scroll

Description

select And Scroll JTable

Demo Code


//package com.java2s;

import java.awt.Point;
import java.awt.Rectangle;

import javax.swing.JTable;

import javax.swing.JViewport;

public class Main {
    public static void selectAndScroll(JTable table, int rowIndex) {
        table.getSelectionModel().setSelectionInterval(rowIndex, rowIndex);
        scrollToVisible(table, rowIndex);
    }//  www . ja v a  2s . c o m

    public static void scrollToVisible(JTable table, int rowIndex) {
        scrollToVisible(table, rowIndex, 0);
    }

    public static void scrollToVisible(JTable table, int rowIndex,
            int vColIndex) {
        if (!(table.getParent() instanceof JViewport))
            return;

        setViewPortPosition((JViewport) table.getParent(),
                table.getCellRect(rowIndex, vColIndex, true));
    }

    private static void setViewPortPosition(JViewport viewport,
            Rectangle position) {
        // The location of the viewport relative to the object
        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)
        position.setLocation(position.x - pt.x, position.y - pt.y);

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

Related Tutorials