In Swing programming with JTable, sometimes we need to scroll the table view to a given row programmatically. If the specified row is not visible, then it will be brought to the visible area. For example: when the user adds a new row to the table, scroll the table view to the newly created row. The table can have many rows and not all are visible, so the newly created row should be brought to the visible area. To do that, follow these two steps:

  • Gets a rectangle for the cell that lies at the intersection of row and column, by using the getCellRect() method of the JTable class.
  • Call the scrollRectToVisible() method which the JTable extends from JComponent. Pass the rectangle object retrieved from the first step as this method’s argument. The table forwards the scrollRectToVisible() message to its parent which is usually a JScrollPane which performs the scrolling.

Here’s an example code snippets that does such scrolling:

JTable table = ...// create a new table

// IMPORTANT: the table must be added to a scroll pane
// in order to have the scrolling works
JScrollPane scrollPane = new JScrollPane(table);

int rowIndex = 20;
int columnIndex = 0;
boolean includeSpacing = true;

Rectangle cellRect = table.getCellRect(rowIndex, columnIndex, includeSpacing);

table.scrollRectToVisible(cellRect);

NOTE: The table should be wrapped inside a JScrollPane, otherwise the scrolling may not work.

For your convenience, we created a demo Swing program which looks like the following screenshot:

JTable Row Scrolling Example

This Swing program shows a table which has 15 rows of data. Enter the row number into the text field, and then click the Scroll to button, the specified row (0-based index) will be scrolled to the visible area. You can download source code and executable JAR file of this nice program in the attachments section.

 

Related JTable Tutorials:

 

API References:


About the Author:

is certified Java programmer (SCJP and SCWCD). He began programming with Java back in the days of Java 1.4 and has been passionate about it ever since. You can connect with him on Facebook and watch his Java videos on YouTube.



Attachments:
Download this file (JTableRowScrollingExample.zip)JTableRowScrollingExample.zip[Source code and executable JAR file]9 kB

Add comment

   


Comments 

#2Henrique2021-07-24 09:38
Wow! I was looking for that! Thanks!
Quote
#1Christian Davis2021-07-07 19:16
Gracias por la ayuda, saludos desde México.
Quote