How to add a new row to JTable with insertRow() in Java Swing

Java 8Object Oriented ProgrammingProgrammingSwing

Let us first create a table with DefaulTabelMode −

DefaultTableModel tableModel = new DefaultTableModel();
JTable table = new JTable(tableModel);

Now, add a column to the table −

tableModel.addColumn("Languages");

The insertRow() method will now add a row −

tableModel.insertRow(0, new Object[] { "CSS" });
tableModel.insertRow(0, new Object[] { "HTML5" });
tableModel.insertRow(0, new Object[] { "JavaScript" });
tableModel.insertRow(0, new Object[] { "jQuery" });

The following is an example to add a new row to JTable −

Example

package my;
import javax.swing.JFrame;
import javax.swing.JScrollPane;
import javax.swing.JTable;
import javax.swing.table.DefaultTableModel;
public class SwingDemo {
   public static void main(String[] argv) throws Exception {
      DefaultTableModel tableModel = new DefaultTableModel();
      JTable table = new JTable(tableModel);
      tableModel.addColumn("Languages");
      tableModel.insertRow(0, new Object[] { "CSS" });
      tableModel.insertRow(0, new Object[] { "HTML5" });
      tableModel.insertRow(0, new Object[] { "JavaScript" });
      tableModel.insertRow(0, new Object[] { "jQuery" });
      tableModel.insertRow(0, new Object[] { "AngularJS" });
      // adding a new row
      tableModel.insertRow(tableModel.getRowCount(), new Object[] { "ExpressJS" });
      JFrame f = new JFrame();
      f.setSize(550, 350);
      f.add(new JScrollPane(table));
      f.setVisible(true);
   }
}

This will produce the following output −

raja
Published on 04-Jun-2019 07:27:57
Advertisements