2017-04-11 104 views
0

我知道有這樣的堆棧溢出與接受的答案,但我剛剛瞭解swingWorker 許多問題,我知道我必須在代碼中的某處使用取消(真)方法,但無法弄清楚如何使用上按下stop_button停止SwingWorker與停止按鈕

計劃是完全運行我已經刪除了額外的代碼是沒有必要的,我只是需要知道如何編寫內這種風格的代碼停止工作器這種方法。

,也是我正在使用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

'SwingWorker'具有['cancel'](https://docs.oracle.com/javase/8/doc s/api/javax/swing/SwingWorker.html#cancel-boolean-),在你的'SwingWorker'中你應該檢查['isCancelled'](https://docs.oracle.com/javase/8/docs/api /javax/swing/SwingWorker.html#isCancelled--)。你應該看看[取消後臺任務](https://docs.oracle.com/javase/tutorial/uiswing/concurrency/cancel.html) - 這一切都假設你正在做的事是可中斷的 – MadProgrammer

+0

@MadProgrammer先生我已經讀過,但無法理解如何在此代碼中使用它:( –

+0

沒有關於你的'doInBackground'方法做什麼的一些想法,這是我們給你提供的幫助 – MadProgrammer

回答

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; 
      //... 
     } 

    }; 
    //... 

然後,您需要監視SwingWorkerisCancelled狀態。

你檢查你做任何「顯著」工作之前,一些攔截功能可能不中斷

@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; 
} 

最後,你需要調用cancelSwingWorker的情況下是很重要的......

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

坦率地說,這只是編程101

+0

謝謝:) 我已經聲明瞭shouldContinue glo bal變量並將其更改爲false。你的代碼幫助我瞭解我需要做什麼:) 順便說一句編程101是什麼? –

+0

編程101是可以應用於任何語言/ API的基本概念和規則,這些是您應該在早期學到的概念。我指的是需要參考您希望使用的對象。另外,不應該改變shouldContinue的上下文,這就是測試的意義(我認爲),但如果你嘗試改變它的狀態在SwingWorker的線程上下文外面,你會遇到問題 – MadProgrammer