简体   繁体   中英

my code does not work properly what is wrong with it? SwingWorker

I have an issue with my swing project , and after long time, I found that I have a concurrency issue. Nevertheless, I am clueless about concurrency issues ,and I just try to learn. My project in nutshell is a database that gets connected to a JTable . When some operations such as enter, update, and delete happens, it affects both database which is derby and JTable at the same time. I use SwingWorker and invokeLater in my code. Sometimes it works, but some other times it doesnot work. my code is as follows Note: I implement AbstractTableModel for my JTable which I advice I should have used DefualtTableModel . the following code is for deleting part and I think I can apply the same functionality for other operations. am I right about it?

private void deleteJBActionPerformed(java.awt.event.ActionEvent evt) {                                         

        deleteDB = new DeleteDB();
        deleteDB.execute();

}                                        
class DeleteDB extends SwingWorker<Void, Void> {

    @Override
    public Void doInBackground() {
        try {
            ed.deleteQuery(name1);
        } catch (SQLException ex) {
            Logger.getLogger(MyFrame.class.getName()).log(Level.SEVERE, null, ex);
            System.out.println("deleteing isuse is " + ex);
        }
        return null;
    }
    @Override
    public void done() {
         if (jTable1.getSelectedRow() >= 0) {
        tm.removeRow(jTable1.getSelectedRow());
          } else {
        System.out.println("nothing is selected");
    }
    name.setText("");
    tel.setText("");
    ed.printData();
        JOptionPane.showMessageDialog(null, "Task completed");
    }

}

Please be kind and help to find out where my problem is. Please inform me if you need more information from me.

Your basic code in the ActionListener is overly complicated.

  1. Code invoked within a listener executes on the Event Dispatch Thread, so there is no need for the SwingUtilities.invokeLater()
  2. for the same reason you don't need the synchronize block.

I would place all the code in the SwingWorker. That is, first you should delete the data from the database (since this is the functionality that is most likely to fail). If the deletete completes successfully then I would remove the row from the TableModel. So you could need to "publish" the row that you want to be deleted within the doInBackground() method. Then the code that executes in the process() method of the SwingWorker will automatically run on the EDT.

See Tasks That Have Intermediate Results for more information.

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