Here you can find the source of tableCenterScroll(JPanel panel, JTable table, int row)
public static void tableCenterScroll(JPanel panel, JTable table, int row)
//package com.java2s; /******************************************************************************** * The contents of this file are subject to the GNU General Public License * * (GPL) Version 2 or later (the "License"); you may not use this file except * * in compliance with the License. You may obtain a copy of the License at * * http://www.gnu.org/copyleft/gpl.html * * * * Software distributed under the License is distributed on an "AS IS" basis, * * without warranty of any kind, either expressed or implied. See the License * * for the specific language governing rights and limitations under the * * License. * * * * This file was originally developed as part of the software suite that * * supports the book "The Elements of Computing Systems" by Nisan and Schocken, * * MIT Press 2005. If you modify the contents of this file, please document and * * mark your changes clearly, for the benefit of others. * ********************************************************************************/ import java.awt.*; import javax.swing.*; public class Main { /**/*from ww w. ja va2s . c o m*/ * Scrolls the given table such that the given row will be centered. * Also required are the containing panel and the number of visible rows in the table. */ public static void tableCenterScroll(JPanel panel, JTable table, int row) { JScrollPane scrollPane = (JScrollPane) table.getParent().getParent(); JScrollBar bar = scrollPane.getVerticalScrollBar(); int beforeScrollValue = bar.getValue(); Rectangle r = table.getCellRect(row, 0, true); table.scrollRectToVisible(r); panel.repaint(); int afterScrollValue = bar.getValue(); double visibleRowsCount = computeVisibleRowsCount(table); // The scroller moved down if (afterScrollValue > beforeScrollValue) { Rectangle newRectangle = table .getCellRect((int) (Math.min(row + visibleRowsCount / 2, table.getRowCount() - 1)), 0, true); table.scrollRectToVisible(newRectangle); panel.repaint(); } // The scroller moved up. else if (afterScrollValue < beforeScrollValue) { Rectangle newRectangle = table.getCellRect((int) (Math.max(row - visibleRowsCount / 2, 0)), 0, true); table.scrollRectToVisible(newRectangle); panel.repaint(); } } /** * Returns the number of visible rows in the given table. */ public static double computeVisibleRowsCount(JTable table) { return table.getParent().getBounds().getHeight() / table.getRowHeight(); } }