Java Swing How to - Add/Get data from DefaultTableModel








Question

We would like to know how to add/Get data from DefaultTableModel.

Answer

import java.util.ArrayList;
import java.util.List;
//w  w w.j  ava2 s  . c o  m
import javax.swing.table.DefaultTableModel;

public class Main {
  public static void main(String s[]) {
    DefaultTableModel model = new DefaultTableModel();

    model.addColumn("Col1");
    model.addColumn("Col2");

    model.addRow(new Object[] { "1", "v2" });
    model.addRow(new Object[] { "2", "v2" });

    List<String> numdata = new ArrayList<String>();
    for (int count = 0; count < model.getRowCount(); count++) {
      numdata.add(model.getValueAt(count, 0).toString());
    }

    System.out.println(numdata);
  }
}