【问题标题】:remove a selected row from jtable on button click单击按钮时从 jtable 中删除选定的行
【发布时间】:2014-06-21 07:56:52
【问题描述】:
我想从 java 中的表中删除选定的行。
该事件应在按钮单击时执行。
如果有人提供帮助,我将不胜感激......
例如,有一个名为 sub_table 的表,它有 3 列,即 sub_id、sub_name、class。
当我从该表中选择其中一行并单击删除按钮时,应删除该特定行..
【问题讨论】:
标签:
java
swing
jtable
actionevent
【解决方案1】:
这很简单。
- 在按钮上添加
ActionListener。
- 从附加到表的模型中删除选定的行。
示例代码:(有 2 列的表格)
Object[][] data = { { "1", "Book1" }, { "2", "Book2" }, { "3", "Book3" },
{ "4", "Book4" } };
String[] columnNames = { "ID", "Name" };
final DefaultTableModel model = new DefaultTableModel(data, columnNames);
final JTable table = new JTable(model);
table.setSelectionMode(javax.swing.ListSelectionModel.SINGLE_SELECTION);
JButton button = new JButton("delete");
button.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent arg0) {
// check for selected row first
if (table.getSelectedRow() != -1) {
// remove selected row from the model
model.removeRow(table.getSelectedRow());
}
}
});