scroll JTable To Center - Java Swing

Java examples for Swing:JTable Scroll

Description

scroll JTable To Center

Demo Code


//package com.java2s;
import javax.swing.*;
import java.awt.*;

public class Main {
    public static void scrollToCenter(JTable table, int rowIndex,
            int vColIndex) {
        if (!(table.getParent() instanceof JViewport)) {
            return;
        }/* w  w  w .  jav a2  s  . c om*/
        JViewport viewport = (JViewport) table.getParent();
        Rectangle rect = table.getCellRect(rowIndex, vColIndex, true);
        Rectangle viewRect = viewport.getViewRect();
        rect.setLocation(rect.x - viewRect.x, rect.y - viewRect.y);

        int centerX = (viewRect.width - rect.width) / 2;
        int centerY = (viewRect.height - rect.height) / 2;
        if (rect.x < centerX) {
            centerX = -centerX;
        }
        if (rect.y < centerY) {
            centerY = -centerY;
        }
        rect.translate(centerX, centerY);
        viewport.scrollRectToVisible(rect);
    }
}

Related Tutorials