Java Program to append a row to a JTable in Java Swing

Java 8Object Oriented ProgrammingProgrammingSwing

To append a row, you can use the addRow() method. Ley us first create a table wherein we need to append a row −

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

Add some columns to the table −

tableModel.addColumn("Language/ Technology");
tableModel.addColumn("Difficulty Level");

Add some rows −

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

Now, if you need to append a row to the table we created above, use the addrow() method −

tableModel.addRow(new Object[] { "WordPress", "Easy" });

The following is an example to append a row to a 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("Language/ Technology");
      tableModel.addColumn("Difficulty Level");
      tableModel.insertRow(0, new Object[] { "CSS", "Easy" });
      tableModel.insertRow(0, new Object[] { "HTML5", "Easy"});
      tableModel.insertRow(0, new Object[] { "JavaScript", "Intermediate" });
      tableModel.insertRow(0, new Object[] { "jQuery", "Intermediate" });
      tableModel.insertRow(0, new Object[] { "AngularJS", "Difficult"});
      // adding a new row
      tableModel.insertRow(tableModel.getRowCount(), new Object[] { "ExpressJS", "Intermediate" });
      // appending a new row
      tableModel.addRow(new Object[] { "WordPress", "Easy" });
      JFrame f = new JFrame();
      f.setSize(550, 350);
      f.add(new JScrollPane(table));
      f.setVisible(true);
   }
}

Output

raja
Published on 30-May-2019 12:29:21
Advertisements