How to Count Number of Rows and Columns of a JTable
In this tutorial, we are going to see how to count the number of rows and columns of a JTable. To count the number of rows in a JTable, use the method getRowCount(): table.getRowCount()
. To count the number of columns in a JTable, use the method getColumnCount(): table.getColumnCount()
. Here is an example to count the number of rows and columns of a JTable.
Java Program to Count Number of Rows and Columns of a JTable:
import javax.swing.*; import java.awt.*; import javax.swing.table.TableColumnModel; public class Main { public static void main(String[] args) { //create a frame final JFrame frame = new JFrame("Exemple de JTable"); //JTable Headers String[] columns = new String[] { "Id", "Name", "Address", "Hourly rate", "Part time" }; //data for JTable in a 2D table Object[][] data = new Object[][] { {1, "Thomas", "Alaska", 20.0, true }, {2, "Jean", "Arizona", 50.0, false }, {3, "Yohan", "California", 30.0, true }, {4, "Emily", "Florida", 60.0, false }, {5, "Alex", "New York", 10.0, false }, }; //create a JTable with data JTable table = new JTable(data, columns); JScrollPane scroll = new JScrollPane(table); table.setFillsViewportHeight(true); //add table to frame frame.getContentPane().add(scroll); System.out.println("Number of lines = "+table.getRowCount()); System.out.println("Number of columns = "+table.getColumnCount()); frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); frame.setSize(400, 180); frame.setVisible(true); } }
Output: