使用停止按钮停止SwingWorker

时间:2017-04-11 22:50:46

标签: java multithreading swing swingworker

我知道有很多关于堆栈溢出的问题和接受的答案,但我刚刚了解了swingWorker 我知道我必须在代码中的某处使用cancel(true)方法,但无法弄清楚如何在按 stop_button

时使用该方法

程序完全正常运行我删除了额外的代码,这是不必要的,我只需要知道如何在以这种风格编写的代码中停止工作。

我也在使用 SwingUtilities.invokeLater

 package webScrapingForPhoner;    

import java.awt.JobAttributes;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.IOException;
import java.util.concurrent.ExecutionException;

import javax.print.CancelablePrintJob;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import javax.swing.JTextArea;
import javax.swing.JTextField;
import javax.swing.SwingWorker;

import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;



public class rungui extends JFrame {
JLabel label_for_input,label_for_output,label_for_console;
JTextField number_field;
JButton start_button,stop_button;
long number=0;
JTextArea resultx;
String domainFound="";
public JTextArea runner;


//arguments for scrapper
boolean test=true;
JTextArea runnerx;
String finalDomain="no valid page found";
String userAgent="";
read useragentwa;
Long start_index;
String domain=".usdirectory.com";   
String http="http://";
long check=0;


rungui() {
 super("Usdirectory valid url finder");

 setLayout(null);

 label_for_input= new JLabel("input starting number of domain");
 label_for_input.setBounds(10,0,300,25);
 add(label_for_input);

 number_field = new JTextField();
 number_field.setBounds(301,0,300,25);
 add(number_field);

 label_for_output= new JLabel("Result will be displayed here");
 label_for_output.setBounds(10,80,300,25);
 add(label_for_output);
 resultx= new JTextArea();
 resultx.setBounds(10,100,580,60);
 add(resultx);

 label_for_console= new JLabel("pages with no data");
 label_for_console.setBounds(10,175,300,25);
 add(label_for_console);

 runner= new JTextArea();
 runner.setBounds(10,200,580,60);
 add(runner);

 stop_button=new JButton("Stop");
 stop_button.setBounds(200, 40, 80, 40);
 setEnabled(false);

 stop_button.addActionListener(new ActionListener() {

    @Override
    public void actionPerformed(ActionEvent e) {

//what to do here
    }
});
 add(stop_button);
 start_button=new JButton("Start");
 start_button.setBounds(100, 40, 80, 40);
 start_button.addActionListener(new ActionListener() {

@Override
public void actionPerformed(ActionEvent e) {
    try{
    start_index=Long.parseLong(number_field.getText());
    }
    catch (Exception exception){
          JOptionPane.showMessageDialog(null, "please restart program and enter a valid number", "Error", JOptionPane.ERROR_MESSAGE);
        System.exit(0);
    }
    runner.setText("Started , take a seat and relax.");

    start();


}
});
 add(start_button);


 setSize(600, 700);
 setVisible(true);
 setDefaultCloseOperation(this.EXIT_ON_CLOSE);

}

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

    @Override
    protected String doInBackground() throws Exception {
        useragentwa=new read();
        userAgent=useragentwa.close();
        Document page=null;

    while(test){

        finalDomain=http+""+start_index+""+domain;
        check=start_index%20;
        if(check==0){
            useragentwa=new read();
            userAgent=useragentwa.close();
            System.out.println(userAgent);
        }   
        start_index++;
        System.out.println(start_index);
        try {
            page = Jsoup.connect(finalDomain).userAgent(userAgent).timeout(10*1000).get();
        } catch (Exception e) {
        start_index--;
            continue;
        }


            if(page.title().contains("U.S. Directory - Online Yellow Pages")){

                // area may want to append in console text area
                continue;

            }

            else{
                System.out.println("found something : "+finalDomain);
                test=false;
                break;
            }

        }





        return finalDomain;
    }

    protected void done(){

            String hereisdomain;
            try {
                hereisdomain = get();
                resultx.setText(hereisdomain);
            } catch (InterruptedException | ExecutionException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }



    }




};
worker.execute();



}
}

1 个答案:

答案 0 :(得分:2)

首先创建一个实例字段,您可以保留对SwingWorker ...

的引用
public class rungui extends JFrame {

    private SwingWorker<String, Void> worker;
    //..

更改start方法以为其分配实例...

void start() {
    // Check to see if the worker is already running...
    if (worker == null || worker.isDone() || worker.isCancelled()) {
        worker = new SwingWorker<String, Void>() {

        @Override
        protected String doInBackground() throws Exception {
            //...
        }

        protected void done() {
            worker = null;
            //...
        }

    };
    //...

然后,您需要监控isCancelled的{​​{1}}状态。

在执行任何“重要”工作之前检查是很重要的,因为某些阻止功能可能无法中断

SwingWorker

最后,您需要在@Override protected String doInBackground() throws Exception { useragentwa = new read(); userAgent = useragentwa.close(); Document page = null; boolean shouldContinue = !isCancelled() || test; while (shouldContinue) { if (isCancelled()) { shouldContinue = false; continue; } finalDomain = http + "" + start_index + "" + domain; check = start_index % 20; if (check == 0) { useragentwa = new read(); userAgent = useragentwa.close(); System.out.println(userAgent); } if (isCancelled()) { shouldContinue = false; continue; } start_index++; System.out.println(start_index); try { page = Jsoup.connect(finalDomain).userAgent(userAgent).timeout(10 * 1000).get(); } catch (Exception e) { start_index--; continue; } if (isCancelled()) { shouldContinue = false; continue; } if (page.title().contains("U.S. Directory - Online Yellow Pages")) { // area may want to append in console text area continue; } else { System.out.println("found something : " + finalDomain); test = false; shouldContinue = false; continue; } } return finalDomain; } 的实例上调用cancel ...

SwingWorker

老实说,这只是编程101