Java Swing How to - Add rows to JTable using a loop








Question

We would like to know how to add rows to JTable using a loop.

Answer

import javax.swing.JFrame;
import javax.swing.JScrollPane;
import javax.swing.JTable;
import javax.swing.table.DefaultTableModel;
//from   w  ww. ja va 2s  .co m
public class Main {
  public static void main(String[] args) {
    Object[][] rowData = {};
    Object[] columnNames = { "Column 1", "Column 2", "Column 3" };

    DefaultTableModel listTableModel;
    listTableModel = new DefaultTableModel(rowData, columnNames);
    for (int i = 1; i < 25; i++) {
      String rowString = "Quiz #" + i;
      listTableModel.addRow(new Object[] { rowString, "ICON", "ICON" });
    }


    JTable listTable;
    listTable = new JTable(listTableModel);
    listTable.setAutoResizeMode(JTable.AUTO_RESIZE_OFF);
    listTable.setCellEditor(null);
    listTable.setBounds(37, 143, 397, 183);

    JFrame frame = new JFrame();
    frame.add(new JScrollPane(listTable));
    frame.setVisible(true);
    frame.pack();
  }
}