delete JTable Row - Java Swing

Java examples for Swing:JTable Row

Description

delete JTable Row

Demo Code


//package com.java2s;
import java.util.Arrays;
import javax.swing.JTable;
import javax.swing.table.DefaultTableModel;
import javax.swing.table.TableColumnModel;

public class Main {
    public static void deleteRow(JTable table, int column, Object value) {
        int count = table.getRowCount();
        int[] rows = new int[count];
        int index = 0;

        for (int i = 0; i < count; i++) {
            if (value.equals(table.getValueAt(i, column))) {
                rows[index++] = i;/* w  ww .  ja  v  a 2s . c om*/
            }
        }

        deleteRows(table, Arrays.copyOf(rows, index));
    }

    public static void deleteRow(JTable table, Object header, Object value) {
        table.setAutoCreateRowSorter(false);

        int cols = table.getColumnCount();
        TableColumnModel model = table.getColumnModel();

        for (int i = 0; i < cols; i++) {
            if (header.equals(model.getColumn(i).getHeaderValue())) {
                deleteRow(table, i, value);
                break;
            }
        }

        table.setAutoCreateRowSorter(true);
    }

    public static void deleteRows(JTable table, int[] rows) {
        if (rows == null)
            return;

        Arrays.sort(rows);

        DefaultTableModel model = (DefaultTableModel) table.getModel();

        for (int i = rows.length - 1; i >= 0; i--) {
            model.removeRow(rows[i]);
        }
    }
}

Related Tutorials