Java Swing How to - Make a Cell Visible in JTable








Question

We would like to know how to make a Cell Visible in JTable.

Answer

 /*from w  ww  .ja  va 2 s . c  o  m*/


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

import javax.swing.JTable;
import javax.swing.JViewport;

public class Main {
  public static void main(String[] argv) throws Exception {
    JTable table = new JTable(10, 5);
    
    int rowIndex = 1;
    int vColIndex = 2;
    scrollToVisible(table, rowIndex, vColIndex);

  }

  public static void scrollToVisible(JTable table, int rowIndex, int vColIndex) {
    if (!(table.getParent() instanceof JViewport)) {
      return;
    }
    JViewport viewport = (JViewport) table.getParent();
    Rectangle rect = table.getCellRect(rowIndex, vColIndex, true);
    Point pt = viewport.getViewPosition();
    rect.setLocation(rect.x - pt.x, rect.y - pt.y);
    viewport.scrollRectToVisible(rect);
  }
}