How do you remove selected rows from a JTable?

前端 未结 18 1173
情话喂你
情话喂你 2020-12-30 03:26

I\'ve tried this:

public void removeSelectedFromTable(JTable from)
{
    int[] rows = from.getSelectedRows();
    TableModel tm= from.getModel();

    while(         


        
相关标签:
18条回答
  • 2020-12-30 04:08
    int[] selectedRows = table.getSelectedRows();
    List<Object> selectedObjects = new ArrayList<Object>();
    for (int row : selectedRows) {
        selectedObjects.add(tableModel.getObject(row));
    }
    for (Object obj : selectedObjects) {
        tableModel.removeObject(obj);
    }
    

    // My TableModel is a subclass of this:

    public abstract class ListTableModel<T> extends AbstractTableModel {
    
        private List<T> data;
    
        public void setData(List<T> data) {
            this.data = data;
        }
    
        public T getObject(int row) {
            return data.get(row);
        }
    
        @Override
        public int getRowCount() {
            return data.size();
        }
    
    }
    
    0 讨论(0)
  • 2020-12-30 04:10

    The stream solution above doesn't take into account sorting, it may be fixed this way:

            IntStream.of(table.getSelectedRows())
                .boxed().map(i -> table.convertRowIndexToModel(i))
                .sorted(Collections.reverseOrder())
                .forEach(((DefaultTableModel)table.getModel())::removeRow);
    
    0 讨论(0)
  • 2020-12-30 04:11
    int[] selectedRows = getTable().getSelectedRows();
            if (selectedRows.length > 0) {
                for (int i = selectedRows.length - 1; i >= 0; i--) {
                    tableModel.removeRow(selectedRows[i]);
                }
            }
    
    0 讨论(0)
  • 2020-12-30 04:12

    It is woked for me.enter code here

    public void removeSelectedFromTable(JTable from)
        {
            int[] rows = from.getSelectedRows();
            DefaultTableModel tm = (DefaultTableModel) from.getModel();
            for (int i = rows.length-1; i >= 0; i--) {
                tm.removeRow(rows[i]);
            }
    }
    
    0 讨论(0)
  • 2020-12-30 04:13

    try this is perfect work and simple

    DefaultTableModel df1 = (DefaultTableModel) jTable1.getModel();
        int rs[] = jTable1.getSelectedRows();
        for (int i = rs.length-1; i >=0 ; i--) {
    
            int k = rs[i];
    
            df1.removeRow(k);
    
        }
    
    0 讨论(0)
  • 2020-12-30 04:13

    The code below will work:

    do {
        ((DefaultTableModel) jXTable1.getModel()).removeRow(jXTable1.getSelectedRows()[0]);
    } while (jXTable1.getSelectedRowCount() > 0);
    
    0 讨论(0)
提交回复
热议问题