-1

我有很多行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;
}
4

3 回答 3

5

来自 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 中的并发以获取更多信息。

于 2012-10-09T08:31:39.973 回答
5

您必须在表格模型中执行此操作。例如,如果你使用javax.swing.table.DefaultTableModel你可以调用它的removeRow()方法。

于 2012-10-09T08:05:04.560 回答
3

您发布的代码中有几个错误 - actionPerformedjButton1 没有,而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并试图从表中删除一个组件。

于 2012-10-09T08:03:45.577 回答