Java 使用停止按钮停止SwingWorker

Java 使用停止按钮停止SwingWorker,java,multithreading,swing,swingworker,Java,Multithreading,Swing,Swingworker,我知道在stack overflow上有很多这样的问题,答案是可以接受的,但我刚刚了解了swingWorker 我知道我必须在代码中的某个地方使用cancel(true)方法,但在按下stop_按钮时,我不知道如何使用该方法 程序正在完美地运行,我已经删除了多余的代码,这是不必要的,我只需要知道如何在这种风格的代码中停止工作 我还使用SwingUtilities.invokeLater 打包webScrapingForPhoner; 导入java.awt.JobAttributes; 导入jav

我知道在stack overflow上有很多这样的问题,答案是可以接受的,但我刚刚了解了swingWorker 我知道我必须在代码中的某个地方使用cancel(true)方法,但在按下stop_按钮时,我不知道如何使用该方法

程序正在完美地运行,我已经删除了多余的代码,这是不必要的,我只需要知道如何在这种风格的代码中停止工作

我还使用SwingUtilities.invokeLater

打包webScrapingForPhoner;
导入java.awt.JobAttributes;
导入java.awt.event.ActionEvent;
导入java.awt.event.ActionListener;
导入java.io.IOException;
导入java.util.concurrent.ExecutionException;
导入javax.print.CancelablePrintJob;
导入javax.swing.JButton;
导入javax.swing.JFrame;
导入javax.swing.JLabel;
导入javax.swing.JOptionPane;
导入javax.swing.JTextArea;
导入javax.swing.JTextField;
导入javax.swing.SwingWorker;
导入org.jsoup.jsoup;
导入org.jsoup.nodes.Document;
公共类rungui扩展了JFrame{
JLabel label_用于_输入,label_用于_输出,label_用于_控制台;
JTextField number_字段;
JButton启动按钮、停止按钮;
长数=0;
JTextArea resultx;
字符串domainFound=“”;
公共区域跑步者;
//支持“刮刀”的理由
布尔检验=真;
jtextarearunnerx;
String finalDomain=“未找到有效页面”;
字符串userAgent=“”;
读useragentwa;
长启动指数;
String domain=“.usdirectory.com”;
字符串http=“http://”;
长检查=0;
rungui(){
超级(“Usdirectory有效url查找器”);
setLayout(空);
用于输入的标签=新的JLabel(“域的输入起始编号”);
为输入设置标签(10,0300,25);
添加(为输入添加标签);
number_field=new JTextField();
数字(301,0300,25);;
添加(数字_字段);
_输出的标签_=新的JLabel(“结果将在此处显示”);
标签_用于_输出.立根(10,80300,25);
添加(为输出添加标签);
resultx=新的JTextArea();
结果立根数(10100580,60);
添加(resultx);
用于控制台的标签=新的JLabel(“没有数据的页面”);
控制台立根的标签(10175300,25);
添加(为控制台添加标签);
runner=新的JTextArea();
转轮.立根(10200580,60);
添加(跑步者);
停止按钮=新按钮(“停止”);
停止按钮。立根(200,40,80,40);
setEnabled(假);
停止按钮。添加ActionListener(新建ActionListener(){
@凌驾
已执行的公共无效操作(操作事件e){
//在这里做什么
}
});
添加(停止按钮);
开始按钮=新按钮(“开始”);
启动按钮。立根(100,40,80,40);
启动按钮。添加ActionListener(新建ActionListener(){
@凌驾
已执行的公共无效操作(操作事件e){
试一试{
start_index=Long.parseLong(number_field.getText());
}
捕获(异常){
showMessageDialog(null,“请重新启动程序并输入有效数字”,“错误”,JOptionPane.Error\u消息);
系统出口(0);
}
runner.setText(“开始,坐下并放松”);
start();
}
});
添加(启动按钮);
设置大小(600700);
setVisible(真);
setDefaultCloseOperation(在关闭时退出);
}
void start(){
SwingWorker worker=新SwingWorker(){
@凌驾
受保护的字符串doInBackground()引发异常{
useragentwa=新读();
userAgent=useragentwa.close();
单据页=空;
while(测试){
finalDomain=http+“”+开始索引+“”+域;
检查=开始索引%20;
如果(检查==0){
useragentwa=新读();
userAgent=useragentwa.close();
System.out.println(用户代理);
}   
start_index++;
System.out.println(开始索引);
试一试{
page=Jsoup.connect(finalDomain).userAgent(userAgent).timeout(10*1000.get();
}捕获(例外e){
开始索引--;
继续;
}
如果(page.title()包含(“美国目录-在线黄页”)){
//区域可能要追加到控制台文本区域中
继续;
}
否则{
System.out.println(“找到某物:+finalDomain”);
测试=假;
打破
}
}
返回最终域;
}
受保护的void done(){
这里是字符串域;
试一试{
hereisdomain=get();
resultx.setText(此处为域);
}捕获(中断异常|执行异常e){
//TODO自动生成的捕捉块
e、 printStackTrace();
}
}
};
worker.execute();
}
}

首先创建一个实例字段,您可以维护对
SwingWorker
的引用

public class rungui extends JFrame {

    private SwingWorker<String, Void> worker;
    //..
    stop_button.addActionListener(new ActionListener() {
        @Override
        public void actionPerformed(ActionEvent e) {
            if(worker != null && !worker.isCancelled() && !worker.isDone()) {
                worker.cancel(true);
            }
        }
    });
然后,您需要监视
SwingWorker
isCancelled
状态

在做任何“重要”的工作之前检查是很重要的,因为某些阻塞功能可能是不可中断的

@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;
}
最后,您需要在
SwingWorker
的实例上调用
cancel

public class rungui extends JFrame {

    private SwingWorker<String, Void> worker;
    //..
    stop_button.addActionListener(new ActionListener() {
        @Override
        public void actionPerformed(ActionEvent e) {
            if(worker != null && !worker.isCancelled() && !worker.isDone()) {
                worker.cancel(true);
            }
        }
    });

老实说,这只是编程101

从创建一个实例字段开始,您可以维护对
SwingWorker
的引用

public class rungui extends JFrame {

    private SwingWorker<String, Void> worker;
    //..
    stop_button.addActionListener(new ActionListener() {
        @Override
        public void actionPerformed(ActionEvent e) {
            if(worker != null && !worker.isCancelled() && !worker.isDone()) {
                worker.cancel(true);
            }
        }
    });
然后,您需要监视
SwingWorker
isCancelled
状态

在做任何“重要”的工作之前检查是很重要的,因为某些阻塞功能可能是不可中断的

@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;
}
最后,您需要在
SwingWorker
的实例上调用
cancel

public class rungui extends JFrame {

    private SwingWorker<String, Void> worker;
    //..
    stop_button.addActionListener(new ActionListener() {
        @Override
        public void actionPerformed(ActionEvent e) {
            if(worker != null && !worker.isCancelled() && !worker.isDone()) {
                worker.cancel(true);
            }
        }
    });

老实说,这只是编程101

SwingWorker
有一个,在您的
SwingWorker
中,您应该检查一下。你应该看看——这一切都假设你所做的是interruptable@MadProgrammer先生,我已经读过了,但无法理解如何在这个代码中使用它:(不知道你的
doInBackground
方法在做什么,这就像我们给你的帮助一样“做什么”