2016-03-11 48 views
2

我正在通過Herbert Schidlt的「The Complete Reference」學習java。 在這本書中,我們建議如果你的任何一部分GUI需要做一件可能需要更長時間的事件,那麼我們應該把它作爲一個新的Thread來實現。如何在JButton上運行線程?

所以,我做了一個GUI來發送郵件到我的收件箱,它工作正常,但它需要2-3秒發送郵件,因此發送按鈕也需要一些時間來恢復到正常狀態(它保持按下直到監聽者回應,如在監聽器中,我已經實現了發送郵件的代碼)。

爲了避免這種情況,我試圖在這個「發送」按鈕上運行一個線程,這樣當按下按鈕時,將生成一個mouseEvent,該mouseEvent上的&,我想運行該線程,以便監聽器立即迴應,郵件通過線程發送。

我該如何實施此方案?我嘗試在MouseEvent中實現新的Runnable作爲內部類,但是我不知道如何調用啓動方法!

代碼很大,所以我只在這裏放置它的「發送按鈕」代碼。

sendButton.addMouseListener(new MouseAdapter(){ 
    public void mouseClicked(MouseEvent me){ 

    String id=emailIdField.getText(); 
    String subject=subjectField.getText(); 
    String body=mailBodyArea.getText();     
    String user= "[email protected]"; 
    String pass="password"; 
    String host="smtp.gmail.com"; 
    sendEmail= new SendEmail(); // class which actually sends the mail. defined in other file. 
    sendEmail.sendMail(id, user, subject ,body ,host, user, pass); 
} 
}); 

我想運行這個MouseClicked函數中的代碼作爲一個新的線程。我到目前爲止所嘗試的是,

sendButton.addMouseListener(new MouseAdapter(){ 
    public void mouseClicked(MouseEvent me){ 

    new Runnable(){ 

       public void run(){ 
        String id=emailIdField.getText(); 
      String subject=subjectField.getText(); 
      String body=mailBodyArea.getText(); 
      System.out.println(id); 
      System.out.println(subject); 
      System.out.println(body); 
      String user= "[email protected]"; 
      String pass="impe(*&amit"; 
      String host="smtp.gmail.com"; 
      sendEmail= new SendEmail(); 
      sendEmail.sendMail(id, user, subject ,body ,host, user, pass); 


       } 
      }; 
}); 

但現在我不知道我該如何調用此線程的啓動方法?請指教。

+0

線程t =新主題(可運行); t.start(); – rkosegi

+0

@rkosegi我在哪裏寫這句話? –

回答

1

內部mouseCliked函數add:

new Thread() { 
public void run() { 
    String id=emailIdField.getText(); 
    String subject=subjectField.getText(); 
    String body=mailBodyArea.getText(); 
    System.out.println(id); 
    System.out.println(subject); 
    System.out.println(body); 
    String user= "[email protected]"; 
    String pass="impe(*&amit"; 
    String host="smtp.gmail.com"; 
    sendEmail= new SendEmail(); 
    sendEmail.sendMail(id, user, subject ,body ,host, user, pass); 
} 
}.start(); 
+0

非常感謝。有效 ! :) –

+0

這個例子有效,但它是一個不好的做法的例子,即:每次你想要執行一個任務時創建一個'new Thread'。最好使用_thread pool_(例如,通過'ExecutorService'或通過使用'SwingWorker'),因爲創建和銷燬Thread對象代價很高。在這種情況下,不會造成任何危害,因爲系統可以比用戶點擊按鈕更快地創建和銷燬線程,但即使如此,爲短期任務「調用」新線程「也是一種壞習慣。 –