2015-06-09 38 views
1

下載我建立一個下載管理器中的JavaFX如何暫停和恢復用JavaFX

我已經加入的功能,下載按鈕,初始化比也被正確執行一個下載新task.More。

但是我需要添加暫停和恢復功能。請告訴如何使用執行程序來實現它。通過Executors的執行功能,任務正在啓動,但是如何暫停&然後恢復?

下面我顯示我的代碼的相關部分。請告訴你是否需要更多細節。謝謝。

主要類

public class Controller implements Initializable { 

    public Button addDownloadButton; 
    public Button pauseResumeButton; 
    public TextField urlTextBox; 
    public TableView<DownloadEntry> downloadsTable; 
    ExecutorService executor; 

    @Override 
    public void initialize(URL location, ResourceBundle resources) { 

     // here tableview and table columns are initialised and cellValueFactory is set 

     executor = Executors.newFixedThreadPool(4); 
    } 

    public void addDownloadButtonClicked() { 
     DownloadEntry task = new DownloadEntry(new URL(urlTextBox.getText())); 
     downloadsTable.getItems().add(task); 
     executor.execute(task); 
    } 


    public void pauseResumeButtonClicked() { 
     //CODE FOR PAUSE AND RESUME 
    } 
} 

DownloadEntry.java

public class DownloadEntry extends Task<Void> { 

    public URL url; 
    public int downloaded; 
    final int MAX_BUFFER_SIZE=50*1024; 
    private String status; 

    //Constructor 
    public DownloadEntry(URL ur) throws Exception{ 
     url = ur; 
     //other variables are initialised here 
     this.updateMessage("Downloading"); 
    } 

    @Override 
    protected Void call() { 
     file = new RandomAccessFile(filename, "rw"); 
     file.seek(downloaded); 
     stream = con.getInputStream(); 

     while (status.equals("Downloading")) { 
      byte buffer=new byte[MAX_BUFFER_SIZE]; 

      int c=stream.read(buffer); 
      if (c==-1){ 
       break; 
      } 
      file.write(buffer,0,c); 
      downloaded += c; 
      status = "Downloading"; 
     } 
     if (status.equals("Downloading")) { 
      status = "Complete"; 
      updateMessage("Complete"); 
     } 
     return null; 
    } 

} 

回答

0

您可能感興趣的Concurrency in JavaFX

我想你也應該看看模式Observer。順便說一句,我認爲你不應該使用常量字符串作爲一個狀態(「下載」等),創建一個枚舉將是一個更好的方法。

在循環中,在讀/寫部分周圍,應該有一個同步機制,由您的暫停/恢復按鈕控制(請參閱兩個鏈接)。

+0

我改變了與字符串的比較。但我已經看過你的鏈接,他們似乎沒有幫助我。在第一個鏈接中沒有提到如何放棄任務。 –

+0

就像概念驗證一樣,您可以在您的DownloadEntry中添加volatile布爾屬性「isPaused」,並在while循環中創建緩衝區後檢查其狀態。如果屬性「isPaused」爲true,則跳過讀/寫步驟。 另外,您需要一個setter(用於isPause),您將在暫停和恢復按鈕中使用它。 但我認爲你希望能夠在同一時間暫停/恢復所有條目。這就是爲什麼我在考慮觀察者模式(您的DownloadEntry應該期待任何暫停/恢復事件)。 – VinceOPS