How to scroll JTable row to visible area programmatically
- Details
- Written by Nam Ha Minh
- Last Updated on 04 July 2019   |   Print Email
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:
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:
- A Simple JTable Example for Display
- How to make editable JTable
- JTable Simple Renderer Example
- JTable column header custom renderer examples
- 6 Techniques for Sorting JTable You Should Know
- How to handle mouse clicking event on JTable column header
- JTable popup menu example
- Setting column width and row height for JTable
- How to create JComboBox cell editor for JTable
Comments