Move the first row to the end of the JTable in Java Swing


To move the first row to the end of the table in Java, use the moveRow() method. It has three parameters. The first two parameters allows you to set the starting and ending row index to be moved. The last parameter sets the destination of the rows to be moved.

As discussed above, move the first row to the end −

tableModel.moveRow(0, 0, tableModel.getRowCount() - 1);

The following is an example to move the first row to the end of the table −

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.addRow(new Object[] { "AngularJS", "Difficult"});
      tableModel.addRow(new Object[] { "CSS", "Easy" });
      tableModel.addRow(new Object[] { "HTML5", "Easy"});
      tableModel.addRow(new Object[] { "JavaScript", "Intermediate" });
      tableModel.addRow(new Object[] { "jQuery", "Intermediate" });
      tableModel.addRow(new Object[] { "WordPress", "Easy" });
      table.setRowHeight(table.getRowHeight() + 5);
      // move first row to the end of the table
      tableModel.moveRow(0, 0, tableModel.getRowCount() - 1);
      JFrame f = new JFrame();
      f.setSize(550, 350);
      f.add(new JScrollPane(table));
      f.setVisible(true);
   }
}

The output is as follows. Here, we have moved the first row (“AngularJS”, “Difficulty”) to the end −

Updated on: 30-Jul-2019

401 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements