简体   繁体   中英

How can remove current row in JTable when click JButton?

I have a number of rows in JTable and each row have remove button. I want to delete the current row when I click the remove button of that row. How can I do this?

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");
        }
    });
} 

Database connection

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;
}

You have to do it in table model. For instance, if you use javax.swing.table.DefaultTableModel you can call its removeRow() method.

UPDATE with Feeback from Kleoptra

Once the button is fired, you need to update the state of the editor and stop the cell editing process.

public void actionPerformed(ActionEvent e) {

    deleteFlag = true;

    // This needs to be called that the model and table have a chance to
    // reset themselves...
    stopCellEditing();

}

You need to return the deleteFlag value from the editors getCellEditorValue

public Object getCellEditorValue() {
    return deleteFlag;
}

Don't forget to reset your flag when the editor is initialised.

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

Now in your model, you will need to capture the event by overriding the setValueAt method of your table model...

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;
    }
}

Now personally, I would always executing any time consuming tasks in background thread or worker. This is will prevent the UI from "hanging".

You might like to have read of Concurrency in Swing for more information.

There are a couple of errors in your posted code - no actionPerformed for jButton1 and no import for ListSelectionModel .

It looks like you are using NetBeans?? You can set the list selection model as a property of the table at design time. As the IDE should also have created the actionPerformed event (as guarded code) I am not sure where that has gone.

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

Removing from the model is sufficient - you don't need to do a remove from the table component. I think this remove is inherited from java.awt.Component and is trying to remove a component from the table.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM