add Data Row to JTable - Java Swing

Java examples for Swing:JTable Row

Description

add Data Row to JTable

Demo Code


import java.util.ArrayList;
import java.util.Collection;
import java.util.Iterator;
import javax.swing.DefaultCellEditor;
import javax.swing.JCheckBox;
import javax.swing.JComboBox;
import javax.swing.JComponent;
import javax.swing.JTable;
import javax.swing.JTextField;
import javax.swing.table.AbstractTableModel;
import javax.swing.table.TableColumn;

public class Main{
    public static void addDataRow(JTable jTable, Collection<?> dataRow)
            throws Exception {

        DynamicTableModel dynamicModel = (DynamicTableModel) jTable
                .getModel();//from   w  w  w.  ja v  a  2  s .c  o m

        ArrayList<Object> newRow = new ArrayList<Object>();

        if (dataRow.size() != dynamicModel.getColumnCount()) {
            throw new Exception(
                    String.format(
                            "The number of columns of data do not match the model. Model[%d] ; Data Row[%d]",
                            dynamicModel.getColumnCount(), dataRow.size()));
        }

        Iterator<?> it = dataRow.iterator();

        while (it.hasNext()) {
            newRow.add(it.next());
        }

        //add this row to model
        dynamicModel.getRows().add(newRow);
        //notify this change        
        dynamicModel.fireTableRowsInserted(dynamicModel.getRows().size(),
                dynamicModel.getRows().size());
    }
}

Related Tutorials