SwingWorker does not stop

So guys, I just got into swing worker and I don't know how to stop it, I tried this way boolean

. its not working, you can change my code so that it works or something! Many thanks!

There is no error to show that it just won't stop!

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


source to share


3 answers


I think the problem is that right after starting swingworker, by calling the method worker.execute()

, you check if there is any stopped == true

. Since the method execute()

does not block, the if statement is evaluated immediately after the call execute()

. At this time, there may be a stop value true

, so your worker will not be canceled. One solution would be to have your worker be an instance member and do it more like this:

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

      



Also, if you have members that are accessible and modified from different threads, you must synchronize this access.

+1


source


You can use SwingWorker

Future

legacy and use functionality isCancelled

and cancel

...

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

      

To be able to cancel a worker, you need a link to it ...



private SwingWorker worker;

//...

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

      

Note. SwingWorker

should not access or reference any UI components (in fact, you should avoid referencing any values ​​out of context where possible), since it runs in the background, you risk (not only) breaking the rules of the only Swing flow, but also having information you rely on has changed during processing.

You must collect all the information you need SwingWorker

and pass that information (via constructor or customization methods) before you start it. This means that the worker works in isolation, without the risk of other data changes that could cause other random problems.

+1


source


You need to check if the value is true stopped

once for each loop, rather than once before the loop. You can rewrite your worker as:

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

      

This, in turn, stops the loop when it tries to execute its next iteration. However, the current iteration will end unless you interrupt the thread or otherwise forcefully stop it.

Also, you will need to make sure that the stopped one is marked volatile where it is declared.

0


source