简体   繁体   English

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

[英]How can remove current row in JTable when click JButton?

I have a number of rows in JTable and each row have remove button. 我在JTable有很多行,每行都有删除按钮。 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. 例如,如果使用javax.swing.table.DefaultTableModel ,则可以调用其removeRow()方法。

UPDATE with Feeback from Kleoptra 来自Kleoptra的Feeback更新

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 您需要从编辑器getCellEditorValue返回deleteFlag

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... 现在在模型中,您将需要通过覆盖表模型的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;
    }
}

Now personally, I would always executing any time consuming tasks in background thread or worker. 现在,就我个人而言,我将始终在后台线程或工作者中执行任何耗时的任务。 This is will prevent the UI from "hanging". 这将防止UI“挂起”。

You might like to have read of Concurrency in Swing for more information. 您可能希望阅读Swing中并发以获取更多信息。

There are a couple of errors in your posted code - no actionPerformed for jButton1 and no import for ListSelectionModel . 您发布的代码中有几个错误-jButton1没有actionPerformedListSelectionModel没有导入。

It looks like you are using NetBeans?? 看来您在使用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. 由于IDE也应该已经创建了actionPerformed事件(作为受保护的代码),所以我不确定该去哪了。

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. 我认为此删除是从java.awt.Component继承的,并且正在尝试从表中删除一个组件。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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