Determine If a Cell Is Visible in a JTable in Java
Description
The following code shows how to determine If a Cell Is Visible in a JTable.
Example
import java.awt.BorderLayout;
import java.awt.Point;
import java.awt.Rectangle;
// w ww . ja v a 2 s . c o m
import javax.swing.JFrame;
import javax.swing.JScrollPane;
import javax.swing.JTable;
import javax.swing.JViewport;
public class Main {
public static void main(String args[]) {
JFrame frame = new JFrame();
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
Object rowData[][] = { { "Row1-Column1", "Row1-Column2", "Row1-Column3" },
{ "Row2-Column1", "Row2-Column2", "Row2-Column3" },
{ "Row3-Column1", "Row3-Column2", "Row3-Column3" }};
Object columnNames[] = { "Column One", "Column Two", "Column Three" };
final JTable table = new JTable(rowData, columnNames);
JScrollPane scrollPane = new JScrollPane(table);
frame.add(scrollPane, BorderLayout.CENTER);
frame.setSize(300, 150);
frame.setVisible(true);
int rowIndex = 1;
int vColIndex = 2;
System.out.println(isCellVisible(table, rowIndex, vColIndex));
}
public static boolean isCellVisible(JTable table, int rowIndex, int vColIndex) {
if (!(table.getParent() instanceof JViewport)) {
return false;
}
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);
return new Rectangle(viewport.getExtentSize()).contains(rect);
}
}
The code above generates the following result.
Home »
Java Tutorial »
Swing »
Java Tutorial »
Swing »