我的 Java GUI 中显示了一个表,用户可以通过单击“添加”按钮向其中添加行。添加到表格的行中的单元格默认都是可编辑的,用户可以根据需要选择每一行/单元格。
我现在想要添加从表中删除行的功能,但我似乎找不到使用 DefaultTableModel
数据类型执行此操作的正确方法。
我已将以下代码添加到“删除行”按钮的操作监听器中:
removeBtn.addActionListener(new ActionListener(){
public void removeRow(){
DefaultTableModel model = (DefaultTableModel)jEntityFilterTable.getModel();
model.removeRow();
}
});
但是,removeRow()
方法需要一个 int
类型的参数(我要删除的行的索引号)。如何从 DefaultTableModel
获取“选定行”?似乎没有一种方法可以让您执行此操作...
最佳答案
可以从表中获取索引。
removeBtn.addActionListener(new ActionListener(){
public void removeRow(){
int selRow = jEntityFilterTable.getSelectedRow();
if(selRow != -1) {
DefaultTableModel model = (DefaultTableModel)jEntityFilterTable.getModel();
model.removeRow(selRow);
}
}
});
关于Java DefaultTableModel-如何删除选定的行?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24605977/