Java JTable Row Visible ensureRowVisible(JTable table, int row)

Here you can find the source of ensureRowVisible(JTable table, int row)

Description

To make sure the row is visible.

License

Open Source License

Parameter

Parameter Description
table a parameter
row a parameter

Declaration

public static void ensureRowVisible(JTable table, int row) 

Method Source Code

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

import java.awt.*;

public class Main {
    /**// w  w w  .j a  v a2 s  .  co m
     * To make sure the row is visible. If the table's horizontal scroll bar is visible, the method will not change the
     * horizontal scroll bar's position.
     *
     * @param table
     * @param row
     */
    public static void ensureRowVisible(JTable table, int row) {
        Rectangle r = table.getVisibleRect();
        // Hack! make above and below visible if necessary
        // TODO: how to center it or make it the first?
        Rectangle rMid = table.getCellRect(row, 0, true);
        Rectangle rBefore = null, rAfter = null;
        if (row < table.getModel().getRowCount() - 1)
            rAfter = table.getCellRect(row + 1, 0, true);
        if (row > 0)
            rBefore = table.getCellRect(row - 1, 0, true);

        int yLow = (int) rMid.getMinY();
        int yHi = (int) rMid.getMaxY();
        int xLow = r.x;
        int xHi = r.x + r.width;

        if (rBefore != null)
            yLow = (int) rBefore.getMinY();

        if (rAfter != null) {
            yHi = (int) rAfter.getMaxY();
        }

        Rectangle rScrollTo = new Rectangle(xLow, yLow, xHi - xLow, yHi
                - yLow);
        if (!r.contains(rScrollTo) && rScrollTo.height != 0) {
            table.scrollRectToVisible(rScrollTo);
        }
    }
}

Related

  1. computeVisibleRowsCount(JTable table)
  2. ensureRowVisible(JTable table, int row)
  3. getFirstVisibleRow(JTable p_Table)
  4. getFirstVisibleRowIndex(JTable table)
  5. getLastVisibleRow(JTable p_Table)