使用停止按钮停止 SwingWorker
Stop SwingWorker with stop button
我知道在 stack-overflow 上有很多这样的问题,答案已被接受,但我刚刚了解了 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();
}
}
首先创建一个实例字段,您可以在其中维护对 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;
//...
}
};
//...
然后,你需要监控SwingWorker
的isCancelled
状态。
在执行任何 "significant" 工作之前进行检查很重要,因为某些阻止功能可能无法中断
@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
stop_button.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
if(worker != null && !worker.isCancelled() && !worker.isDone()) {
worker.cancel(true);
}
}
});
老实说,这只是编程 101
我知道在 stack-overflow 上有很多这样的问题,答案已被接受,但我刚刚了解了 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();
}
}
首先创建一个实例字段,您可以在其中维护对 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;
//...
}
};
//...
然后,你需要监控SwingWorker
的isCancelled
状态。
在执行任何 "significant" 工作之前进行检查很重要,因为某些阻止功能可能无法中断
@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
stop_button.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
if(worker != null && !worker.isCancelled() && !worker.isDone()) {
worker.cancel(true);
}
}
});
老实说,这只是编程 101