[英]How can remove current row in JTable when click JButton?
我在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的Feeback更新
触发按钮后,您需要更新编辑器的状态并停止单元格编辑过程。
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“挂起”。
您发布的代码中有几个错误-jButton1没有actionPerformed
, 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
继承的,并且正在尝试从表中删除一个组件。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.