如何在单击JButton时删除JTable中的当前行?

我在JTable有很多行,每行都有删除按钮。 我想在单击该行的删除按钮时删除当前行。 我怎样才能做到这一点?

 private JButton button; public MyTableButtonEditor1() { button = new JButton("REMOVE"); button.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { DbUtility ViewEmployee =new DbUtility(); ViewEmployee.loadDriver(); ViewEmployee.connect(); ResultSet rs= ViewEmployee.executeDeleteQuery(Employeeid); JOptionPane.showMessageDialog(null, "Employee Removed"); } }); } 

数据库连接

 public ResultSet executeDeleteQuery(String Employeeid ) { PreparedStatement pstmt ; try { pstmt = conn.prepareStatement("DELETE FROM employee WHERE EmployeeId ="+Employeeid ); pstmt.execute(); } catch (SQLException ex){ // handle any errors System.out.println("SQLException: " + ex.getMessage()); System.out.println("SQLState: " + ex.getSQLState()); System.out.println("VendorError: " + ex.getErrorCode()); } return rs; } 

你必须在表格模型中这样做。 例如,如果使用javax.swing.table.DefaultTableModel ,则可以调用其removeRow()方法。

来自Kleoptra的反馈更新

触发按钮后,您需要更新编辑器的状态并停止单元格编辑过程。

 public void actionPerformed(ActionEvent e) { deleteFlag = true; // This needs to be called that the model and table have a chance to // reset themselves... stopCellEditing(); } 

您需要从编辑器getCellEditorValue返回deleteFlag

 public Object getCellEditorValue() { return deleteFlag; } 

初始化编辑器时,不要忘记重置标志。

 public Component getTableCellEditorComponent(JTable table, Object value, boolean isSelected, int row, int column) { deleteFlag = false; // Set up and return your button... } 

现在在您的模型中,您需要通过覆盖表模型的setValueAt方法来捕获事件…

 public void setValueAt(Object aValue, int rowIndex, int columnIndex) { switch (columnIndex) { case indexOfButtonColumn: if (aValue instanceof Boolean && ((Boolean) aValue).booleanValue()) { // Delete row from database... // Update you internal model. DefaultTableModel has a removeRow // method, if you're using it. // Other wise you will need to update your internal model // and fire the rows delete event in order to update the table... fireTableRowsDeleted(rowIndex, rowIndex); } break; } } 

现在,我个人总是在后台线程或工作者中执行任何耗时的任务。 这将阻止UI“挂起”。

您可能希望阅读Swing中的Concurrency以获取更多信息。

您发布的代码中存在一些错误 – 没有针对jButton1的actionPerformed和针对ListSelectionModel导入。

看起来你正在使用NetBeans? 您可以在设计时将列表选择模型设置为表的属性。 由于IDE也应该创建了actionPerformed事件(作为保护代码),我不确定它在哪里。

 model.removeRow(rowid); // this line is all you need //table.remove(rowid); <- this line is probably the error 

从模型中删除就足够了 - 您无需从表组件中删除。 我认为这个remove是从java.awt.Componentinheritance的,并且正在尝试从表中删除一个组件。