我需要从数组列表中删除已删除的行...
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;
}
但我需要将其从我的私有(private)列表 zoz 中删除;
我该怎么做?
最佳答案
我需要将其从我的私有(private)列表 zoz 中删除吗?
zoz.remove(sectedRowIndex); // if table is not sortable
注意:
- 删除所选行后不要再次初始化列表。
DefaultTableModel
未从列表中填充- 在删除行之前检查
tblTabulka.getSelectedRow() != -1
是否选择了该行?
使用Map
而不是List
类似
Map<String,Book> books = new HashMap<String,Book>();
您可以在其中将 isbn 或 id 作为 key 。
<小时/>示例代码:
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());
}
}
});
关于Java-从表模型中删除选定的行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23460393/