Java Swing How to - Delete multiple rows from bean tablemodel








Question

We would like to know how to delete multiple rows from bean tablemodel.

Answer

import java.awt.BorderLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
/*  ww  w .  j  a  va  2  s .  c o  m*/
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JScrollPane;
import javax.swing.JTable;
import javax.swing.table.DefaultTableModel;

public class Main {
  public static void main(String args[]) {
    DefaultTableModel model;
    JTable t = new JTable(model = new DefaultTableModel(0, 1));
    for (int i = 0; i < 10; i++) {
      model.addRow(new Object[] { i });
    }
    JButton removeSelected = new JButton("remove");
    removeSelected.addActionListener(new ActionListener() {
      @Override
      public void actionPerformed(ActionEvent e) {
        int[] selectedRows = t.getSelectedRows();
        for (int i = selectedRows.length - 1; i >= 0; i--) {
          model.removeRow(selectedRows[i]);
          ;
        }
      }
    });
    JFrame f = new JFrame();
    f.add(new JScrollPane(t));
    f.add(removeSelected, BorderLayout.SOUTH);
    f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    f.pack();
    f.setVisible(true);
  }
}