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

lea*_*ner -1 java swing jdbc 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");
        }
    });
} 
Run Code Online (Sandbox Code Playgroud)

数据库连接

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;
}
Run Code Online (Sandbox Code Playgroud)

Ada*_*yga 5

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


Mad*_*mer 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();

}
Run Code Online (Sandbox Code Playgroud)

您需要deleteFlag从编辑器返回值getCellEditorValue

public Object getCellEditorValue() {
    return deleteFlag;
}
Run Code Online (Sandbox Code Playgroud)

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

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

现在在您的模型中,您需要通过覆盖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;
    }
}
Run Code Online (Sandbox Code Playgroud)

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

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

  • 假设按钮_is-a_ cellEditor,上面是该编辑器的actionPerformed - 不,简单错误.但假设你的意思不同:-) (2认同)