SwingWorker没有停止

时间:2014-08-30 22:15:19

标签: java swing swingworker

所以,我刚刚进入摇摆工作者,我不知道如何阻止它我尝试boolean方式。它不能正常工作,你可以编辑我的代码,使其成为可行的方式!非常感谢!

没有错误显示它只是没有停止!

class MessageBox {

    public static void infoBox(String infoMessage, String location)
    {
        JOptionPane.showMessageDialog(null, infoMessage, "Message: " + location, JOptionPane.INFORMATION_MESSAGE);
    }
}

public class GUI extends JFrame 
{
    private JButton button1;
    private JPanel Gpanel;
    private JTextField textField1;
    private JTextField howmany;
    private JLabel countlabel;
    private JLabel statuslabel;
    private JCheckBox anyEmail;
    private JButton stopButton;
    private boolean stopped;


    public GUI() {
        super("Program V0.1");
        this.setIconImage(new ImageIcon(getClass().getResource("icon.png")).getImage());

        setContentPane(Gpanel);
        pack();
        setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
        setVisible(true);

        button1.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                start();
            }
        });
        stopButton.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
            stopped = true;
            }
        });
    }

    private void start() {
        SwingWorker<Void, Void> worker = new SwingWorker<Void, Void>() {

            @Override
            protected Void doInBackground() throws Exception {
                if (!stopped){
                    for (int i = 0; i < Integer.parseInt(howmany.getText()); i++) {
                        if (anyEmail.isSelected()) {

                            URL url = null;
                            try {
                                String Hostemail = "http://example.com/";
                                url = new URL(Hostemail);
                            } catch (MalformedURLException e) {
                                e.printStackTrace();
                            }
                            Map<String, Object> variables = new LinkedHashMap<>();

                            variables.put("email", textField1.getText());
                            variables.put("fullname", "");
                            variables.put("pw", "");
                            variables.put("pw-conf", "");
                            variables.put("digest", "1");
                            variables.put("email-button", "Subscribe");

                            StringBuilder postData = new StringBuilder();
                            for (Map.Entry<String, Object> param : variables.entrySet()) {
                                if (postData.length() != 0) {
                                    postData.append('&');
                                }
                                try {
                                    postData.append(URLEncoder.encode(param.getKey(), "UTF-8"));
                                } catch (UnsupportedEncodingException e) {
                                    e.printStackTrace();
                                }
                                postData.append('=');
                                try {
                                    postData.append(URLEncoder.encode(String.valueOf(param.getValue()), "UTF-8"));
                                } catch (UnsupportedEncodingException e) {
                                    e.printStackTrace();
                                }
                            }
                            byte[] postDataBytes = new byte[0];
                            try {
                                postDataBytes = postData.toString().getBytes("UTF-8");
                            } catch (UnsupportedEncodingException e) {
                                e.printStackTrace();
                            }
                            String line;
                            HttpURLConnection conn = null;
                            try {
                                assert url != null;
                                conn = (HttpURLConnection) url.openConnection();
                            } catch (IOException e) {
                                e.printStackTrace();
                            }
                            try {
                                assert conn != null;
                                conn.setRequestMethod("POST");
                            } catch (ProtocolException e) {
                                e.printStackTrace();
                            }

                            conn.setRequestProperty("Cache-Control", "no-cache,private,Private");

                            conn.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
                            conn.setRequestProperty("Content-Length", String.valueOf(postDataBytes.length));
                            conn.setDoOutput(true);
                            try {
                                conn.getOutputStream().write(postDataBytes);
                            } catch (IOException e) {
                                e.printStackTrace();
                            }

                            BufferedReader in = null;
                            try {
                                in = new BufferedReader(new InputStreamReader(conn.getInputStream(), "UTF-8"));
                            } catch (IOException e) {
                                e.printStackTrace();
                            }
                            try {
                                assert in != null;
                                while ((line = in.readLine()) != null) {

                                    String success = "Your subscription request has been received";
                                    if (line.contains(success)) {
                                        countlabel.setText(String.valueOf(i));
                                    }
                                }
                            } catch (IOException e) {
                                e.printStackTrace();
                            }
                        } else {
                            URL url = null;
                            try {
                                String Host = "http://example2.com";
                                url = new URL(Host);
                            } catch (MalformedURLException e) {
                                e.printStackTrace();
                            }
                            Map<String, Object> variables = new LinkedHashMap<>();

                            variables.put("strEmail", textField1.getText());

                            StringBuilder postData = new StringBuilder();
                            for (Map.Entry<String, Object> param : variables.entrySet()) {
                                if (postData.length() != 0) {
                                    postData.append('&');
                                }
                                try {
                                    postData.append(URLEncoder.encode(param.getKey(), "UTF-8"));
                                } catch (UnsupportedEncodingException e) {
                                    e.printStackTrace();
                                }
                                postData.append('=');
                                try {
                                    postData.append(URLEncoder.encode(String.valueOf(param.getValue()), "UTF-8"));
                                } catch (UnsupportedEncodingException e) {
                                    e.printStackTrace();
                                }
                            }
                            byte[] postDataBytes = new byte[0];
                            try {
                                postDataBytes = postData.toString().getBytes("UTF-8");
                            } catch (UnsupportedEncodingException e) {
                                e.printStackTrace();
                            }
                            String line;
                            HttpURLConnection conn = null;
                            try {
                                assert url != null;
                                conn = (HttpURLConnection) url.openConnection();
                            } catch (IOException e) {
                                e.printStackTrace();
                            }
                            try {
                                assert conn != null;
                                conn.setRequestMethod("POST");
                            } catch (ProtocolException e) {
                                e.printStackTrace();
                            }

                            conn.setRequestProperty("Cache-Control", "no-cache,private,Private");

                            conn.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
                            conn.setRequestProperty("Content-Length", String.valueOf(postDataBytes.length));
                            conn.setDoOutput(true);
                            try {
                                conn.getOutputStream().write(postDataBytes);
                            } catch (IOException e) {
                                e.printStackTrace();
                            }

                            BufferedReader in = null;
                            try {
                                in = new BufferedReader(new InputStreamReader(conn.getInputStream(), "UTF-8"));
                            } catch (IOException e) {
                                e.printStackTrace();
                            }
                            try {
                                statuslabel.setText("Sending Emails...");
                                assert in != null;
                                while ((line = in.readLine()) != null) {

                                    String success = "success";
                                    String error = "not";

                                    if (line.contains(success)) {
                                        countlabel.setText(String.valueOf(i));
                                    } else if (line.contains(error)) {
                                        MessageBox.infoBox("[Email Not Found]: " + textField1.getText(), "Error");
                                        break;
                                    }
                                }
                            } catch (IOException e) {
                                e.printStackTrace();
                            }
                        }
                    }

                }
                statuslabel.setText("Done");
                return null;
            }

        };
        worker.execute();
        if (stopped){
            worker.cancel(true);
        }
    }
}

3 个答案:

答案 0 :(得分:1)

您可以利用SwingWorker Future遗产并使用isCancelledcancel功能......

protected Void doInBackground() throws Exception {
    int i = 0;
    while (!isCancelled() && i < howMany) {
        ...

为了能够取消工人,你需要参考它......

private SwingWorker worker;

//...

stopButton.addActionListener(new ActionListener() {
    @Override
    public void actionPerformed(ActionEvent e) {
        if (worker != null) {
            worker.cancel(true);
        }
    }
});

注意,SwingWorker不应该访问或引用任何UI组件(事实上,你应该尽可能避免引用它之外的任何值),因为它在后台运行,你运行(不仅)违反Swing的单线程规则的风险,而且在处理时还会改变您所依赖的信息。

您应该在开始之前收集SwingWorker所需的所有信息并将该信息传递给它(通过构造函数或setter方法)。这意味着工作人员孤立地运行,没有其他数据更改的风险,这可能会导致其他随机问题。

答案 1 :(得分:1)

我认为问题是,在您通过调用worker.execute()方法启动swingworker之后,立即检查是否stopped == true。由于execute()方法是非阻塞的,因此只需在调用execute()之后评估if语句。此时,已停止的值只能是true,因此您的工作人员不会被取消。一种解决方案是,让您的工作人员成为实例成员,并且更像这样:

private SwingWorker worker;
// ...
stopButton.addActionListener(new ActionListener() {
    @Override
    public void actionPerformed(ActionEvent e) {
        if (worker != null && !worker.isCanceled()) {
            worker.cancel(true);
        }
    }
}); 

此外,如果您有从不同线程访问和更改的成员,则应同步该访问权限。

答案 2 :(得分:0)

一旦每个循环交互,您需要检查stopped是否为真,而不是在循环之前检查一次。您可以将您的工作人员改写为:

    @Override
    protected Void doInBackground() throws Exception {
        for (int i = 0; i < Integer.parseInt(howmany.getText()); i++) {
           if(stopped){return null;}
           //your existing loop contents
        }
    }

这会在尝试执行下一次迭代时停止循环。但是,除非您中断线程或以其他方式强制停止,否则当前迭代将完成。

此外,您需要确保在被声明的地方将被标记为易失性。