我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()
方法。
UPDATE with Feeback from 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();
}
您需要从编辑器返回deleteFlag
值getCellEditorValue
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 中的并发性以获取更多信息。
您发布的代码中有几个错误 - 没有actionPerformed
jButton1 并且没有导入ListSelectionModel
.
看起来您正在使用 NetBeans??您可以设置列表选择模型作为设计时表的属性。由于 IDE 也应该具有创建了actionPerformed
事件(作为受保护的代码)我不确定在哪里走了。
model.removeRow(rowid); // this line is all you need
//table.remove(rowid); <- this line is probably the error
从模型中删除就足够了 - 您无需从表组件。我认为此删除继承自 java.awt.Component
并尝试从表中删除组件。