我想从 java 中的表中删除选定的行。 该事件应在按钮单击时执行。 如果有人帮助,我将非常感谢...
例如,有一个名为 sub_table 的表,其中包含 3 列,即 sub_id、sub_name、class。 当我从该表中选择其中一行并单击删除按钮时,应该删除该特定行..
最佳答案
非常简单。
- 在按钮上添加
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());
}
}
});
关于java - 单击按钮从 jtable 中删除选定的行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23465295/