列出当前正在执行的SwingWorker并将其停止

时间:2015-05-21 07:30:24

标签: java swingworker

我在SwingWorker下面;

public class WorkerTrying extends SwingWorker<Void, Void> {

        Statement stmt;
        Connection con;
        ResultSet rs;
        String connectionUrl = "jdbc:sqlserver://192.168.131.10;" + "databaseName=SomeDB;" + "user=" + "SomeUser" + ";" + "password=" + "SomeUserPassword" + ";";

        public void closeConnection() throws SQLException{
        stmt.close();
        System.out.println("Closed!!!");
        }

        protected Void doInBackground() throws Exception {

            String query = "Select column1,column2 from Table1"
            Class.forName("com.microsoft.sqlserver.jdbc.SQLServerDriver");

            con = DriverManager.getConnection(connectionUrl);
            stmt = con.createStatement();

            rs = stmt.executeQuery(query);

            while (rs.next()){
              //Doing something...
            }

            return null;
        }

        public void done() {               

        }  
    }

正如您可以通过此工作器中的While循环看到一些数据库连接和数据fetchinbg。我的问题是DB Queries有时需要很长时间。我想添加STOP按钮来关闭SwingWorker中的语句和连接,并立即取消它。

我正在尝试下面的停止按钮,但没有帮助;

private void jButton2ActionPerformed(java.awt.event.ActionEvent evt) {                                         
      WorkerTrying workerTrying = new WorkerTrying();
      workerTrying.cancel(true);
    } 

我也有3-4个SwingWorkers。所以我必须先检测出哪一个当前正在运行。

问候。

====更新====

像这样的新停止按钮;

jButtonStop.addActionListener(new java.awt.event.ActionListener() {
    public void actionPerformed(java.awt.event.ActionEvent evt) {
            for(SwingWorker workerTrying : _workers){
                 if(!workerTrying.isDone()){
                    try {
                        ((WorkerTrying)workerTrying).closeConnection();
                    } catch (SQLException ex) {
                        Logger.getLogger(MainGui.class.getName()).log(Level.SEVERE, null, ex);
                    }
                    workerTrying.cancel(true);
                 }
            }

       }
   }
});

====第二次问题更新====

开始按钮动作侦听器就像这样;

startButton.addActionListener(new java.awt.event.ActionListener() {
              public void actionPerformed(java.awt.event.ActionEvent evt) {
                  if(jTextField1.getText().equals("")){
                    final SwingWorker workerTrying = new WorkerTrying();
                    _workers.add(workerTrying);
                    workerTrying.execute();
                  }
                  else{
                    final SwingWorker workerTrying2 = new WorkerTrying2();
                    _workers.add(workerTrying2);
                    workerTrying2.execute();  
                  }
                }
});

您可以看到可以执行SwingWorker的一些条件。

比停止按钮就像这样;

stopButton.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                for (SwingWorker workerTrying : _workers) {
                    if(!workerTrying.isDone()){
                        try {
                            ((WorkerTrying)workerTrying).closeConnection();
                        } catch (SQLException ex) {
                            Logger.getLogger(MainGui.class.getName()).log(Level.SEVERE, null, ex);
                        }
                        workerTrying.cancel(true);
                    }
                }
                for (SwingWorker workerTrying2 : _workers) {
                    if(!workerTrying2.isDone()){
                        try {
                            ((WorkerTrying2)workerTrying2).closeConnection();
                        } catch (SQLException ex) {
                            Logger.getLogger(MainGui.class.getName()).log(Level.SEVERE, null, ex);
                        }
                        workerTrying2.cancel(true);
                    }
                }
            }
        });

如果第一个SwingWorker(workerTrying)执行并尝试停止,那么每个人看起来都没问题。声明已关闭且SwingWorker已成功取消。

但是当第二个SwingWorker(workerTrying2)执行并希望停止时,抛出以下异常;

Exception in thread "AWT-EventQueue-0" java.lang.ClassCastException: testproject.MainGui$WorkerTrying2 cannot be cast to testproject.MainGui$WorkerTrying

1 个答案:

答案 0 :(得分:1)

我使用List来跟踪所有工人。并且阻止了一切。你可以试试这个。

 public class SwingT {
    private List<SwingWorker> _workers = new ArrayList<>();
    public SwingT(){
        JFrame frame = new JFrame("Test Worker");        
        frame.setSize(320, 160);
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        frame.setLayout(new FlowLayout());
        JButton btn = new JButton("Add Work");
        btn.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                SwingWorker workerTrying = new WorkerTrying();
                _workers.add(workerTrying);
                workerTrying.execute();
            }
        });

        JButton btn2 = new JButton("Stop All");
        btn2.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                for(SwingWorker workerTrying : _workers){
                    if(!workerTrying.isDone()){
                        //Close DB Connections
                        ((WorkerTrying)workerTrying).closeConnection();
                        workerTrying.cancel(true);
                    }
                }

            }
        });
        frame.add(btn);
        frame.add(btn2);
        frame.setVisible(true);
    }

    /**
     * @param args
     */
    public static void main(String[] args) {
        new SwingT();

    }

}

<强>更新

public class WorkerTrying  extends SwingWorker<Void, Void> {

public void closeConnection(){
    //Close the connection
    System.out.println("closed");
}

..........
}