Java JTable get table data cell by cell

Description

Java JTable get table data cell by cell


import javax.swing.JFrame;
import javax.swing.JScrollPane;
import javax.swing.JTable;
import javax.swing.table.DefaultTableModel;
import javax.swing.table.TableModel;

public class Main {
   public static void main(String args[]) {
      JFrame frame = new JFrame();
      frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

      DefaultTableModel model = new DefaultTableModel();
      model.setColumnIdentifiers(new Object[] { "Column 1", "Column 2", "Column 3" });

      JTable table = new JTable(model);
      for (int count = 0; count < 3; count++) {
         model.insertRow(count, new Object[] { count, "name", "age" });
      }/*from  w  ww .  ja va 2s  .com*/

      frame.add(new JScrollPane(table));
      frame.setLocationByPlatform(true);
      frame.pack();
      frame.setVisible(true);
      
      int numRows = table.getRowCount();
      int numCols = table.getColumnCount();
      TableModel tableModel = table.getModel();

      System.out.println("Value of data: ");
      for (int i = 0; i < numRows; i++) {
        System.out.print("    row " + i + ":");
        for (int j = 0; j < numCols; j++) {
          System.out.print("  " + tableModel.getValueAt(i, j));
        }
        System.out.println();
      }
   }
}



PreviousNext

Related