Java how to scroll jtable row to visible area programmatically
In Java Swing, you can scroll a JTable
row to the visible area programmatically by using the scrollRectToVisible()
method of the table's JViewport
. Here's an example:
import javax.swing.JFrame; import javax.swing.JScrollPane; import javax.swing.JTable; import javax.swing.SwingUtilities; import javax.swing.table.DefaultTableModel; public class TableExample { public static void main(String[] args) { SwingUtilities.invokeLater(() -> { // Create a table with a default table model JTable table = new JTable(new DefaultTableModel(new Object[][]{{1, "John", "Doe"}, {2, "Jane", "Doe"}, {3, "Bob", "Smith"}}, new Object[]{"ID", "First Name", "Last Name"})); // Add the table to a scroll pane and display it in a frame JFrame frame = new JFrame(); frame.add(new JScrollPane(table)); frame.pack(); frame.setVisible(true); // Scroll the first row of the table to the visible area scrollToVisible(table, 0); }); } private static void scrollToVisible(JTable table, int rowIndex) { // Get the bounds of the cell at the specified row and column table.getCellRect(rowIndex, 0, true); // Scroll the cell to the visible area table.scrollRectToVisible(table.getCellRect(rowIndex, 0, true)); } }
In this example, we create a JTable
with a default table model and add it to a scroll pane in a frame. We then call the scrollToVisible()
method to scroll the first row of the table to the visible area.
The scrollToVisible()
method takes a JTable
and an integer rowIndex
as parameters. It first gets the bounds of the cell at the specified row and column using the getCellRect()
method of the table. It then scrolls the cell to the visible area by calling the scrollRectToVisible()
method of the table's JViewport
.
When you run this example, you will see a JTable
with three rows and three columns. The first row of the table will be scrolled to the visible area programmatically when the application starts.