Java - 从tablemodel中删除选定的行

时间:2014-05-04 19:09:45

标签: java swing jtable defaulttablemodel

我需要从我的arraylist中删除已删除的行...

private GuiIO guiIO;
private DefaultTableModel tableModel;
private List<Book> zoz;


public MyGui() {
    initComponents();
    this.setLocationRelativeTo(this.getRootPane());
    this.guiIO = new GuiIO();

    tableModel = new DefaultTableModel(new String[]{"Znacka", "Model", "Najazdene", "Rok vyroby", "Vykon", "Cena"}, 0);
    this.tblTabulka.setModel(tableModel);
    this.tblTabulka.setSelectionMode(javax.swing.ListSelectionModel.SINGLE_SELECTION);
    tblTabulka.setAutoCreateRowSorter(true);
    TableRowSorter rowSorter = new TableRowSorter(tableModel);
    zoz = guiIO.getAllBook();
}

我的模型删除行的功能:

   private void btnClearActionPerformed(java.awt.event.ActionEvent evt) {
    final int sectedRowIndex = this.tblTabulka.getSelectedRow();
    this.tableModel.removeRow(sectedRowIndex);
    zoz = guiIO.getAllBook();
}

 public List getAllBook() {
    List all_book = new ArrayList<Book>();

    for (Containerable item = this.book.getFirst();
            item!=null;
            item = this.book.getNext())
        all_book.add(item);
    return all_book;
}    

但我需要从我的私人列表中删除它;

我该怎么做?

1 个答案:

答案 0 :(得分:3)

我需要从我的私人列表中删除它吗?

 zoz.remove(sectedRowIndex); // if table is not sortable

注意:

  • 删除所选行后,请勿再次初始化列表。
  • DefaultTableModel未从列表中填充
  • 在删除行之前检查tblTabulka.getSelectedRow() != -1是否选择了行?

使用Map代替List之类的内容

Map<String,Book> books = new HashMap<String,Book>();

您可以将isbn或id作为密钥。


示例代码:

button.addActionListener(new ActionListener() {

    @Override
    public void actionPerformed(ActionEvent arg0) {
        // check for selected row first
        if (tblTabulka.getSelectedRow() != -1) {

            // get value of first cell of selected row
            String isbn= (String)tableModel.getValueAt(tblTabulka.getSelectedRow(), 0);
            books.remove(isbn);

            // remove from the model also
            model.removeRow(tblTabulka.getSelectedRow());
        }
    }
});