2014-09-24 51 views
-1

這是一個垃圾郵件機器人,它會寫入一個字符串,當您按下按鈕時輸入,但是當我按下運行按鈕時JFrame會凍結,並且我無法按它來停止它,繼續運行。我希望能夠在運行時切換按鈕,有什麼建議嗎?當我運行一個機器人時,JFrame被凍結

import java.awt.AWTException; 
import java.awt.FlowLayout; 
import java.awt.Font; 
import java.awt.event.ActionEvent; 
import java.awt.event.ActionListener; 

import javax.swing.JFrame; 
import javax.swing.JTextField; 
import javax.swing.JToggleButton; 
import javax.swing.SwingWorker; 
import javax.swing.UIManager; 

public class Main extends JFrame{ 

    private static final long serialVersionUID = 1L; 

    JFrame frame = new JFrame("SPAM BOT"); 
    JTextField txt = new JTextField(20); 
    JToggleButton btn = new JToggleButton("START"); 

    Font font = new Font("Calibri", Font.PLAIN, 20); 
    Font font2 = new Font("Wildcard", Font.BOLD, 20); 

    public Main(){ 
     sendUI(); 
    } 

    public void sendUI(){ 
     frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); 
     frame.setLayout(new FlowLayout()); 
     frame.setSize(375, 115); 
     frame.setVisible(true); 

     frame.add(txt); 
     frame.add(btn); 

     txt.setFont(font);    
     btn.setFont(font2); 

     btn.addActionListener(new ActionListener(){ 
      public void actionPerformed(ActionEvent e) {    

       String str = txt.getText().toString();                
       if(btn.isSelected()){ 
        btn.setText("STOP");  
        write(true, str); 
        btn.setSelected(false); 

       }else{      
        btn.setText("START"); 
        write(false, str); 
       } 

      } 
     }); 

    } 

    public void write(boolean typing, final String str){ 
     while(typing==true){ 
      SwingWorker<Void, Void> worker = new SwingWorker<Void, Void>(){ 

       @Override 
       protected Void doInBackground() throws Exception { 
        try { 
         Bot bot = new Bot(); 
         //bot.type(str + " "); 
         System.out.println("done"); 
         Thread.sleep(1000); 
        }catch (AWTException e) {} 
        return null; 
       } 
      }; 
      worker.execute(); 
     } 
    } 

    public static void main(String args[]){ 

     try{ 
      UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName()); 
     }catch(Exception e){} 

     Main mo = new Main(); 
    } 


} 

回答

0

那是因爲一切都在一個線程中運行。您應該考慮爲您的機器人創建另一個線程:)

+0

這不提供問題的答案。要批評或要求作者澄清,在他們的帖子下留下評論 - 你總是可以評論你自己的帖子,一旦你有足夠的[聲譽](http://stackoverflow.com/help/whats-reputation),你會能夠[評論任何帖子](http://stackoverflow.com/help/privileges/comment)。 – Jubobs 2014-09-24 17:34:53

+0

爲什麼你認爲這不是OPs發佈的答案?答案是將他的大多數bot邏輯放在單獨的線程中,所以我不明白你在我的評論中看到問題的位置。我不批評他的帖子或他的問題。 – Lemonov 2014-09-24 20:05:53

+0

你可能是對的,但是,作爲評論,你的回答會更合適。你可能想詳細說明一下。 – Jubobs 2014-09-24 20:10:29

0

一般來說,像這樣的過程或任何與網絡相關的過程應該在單獨的線程上運行以防止「凍結」。在使用Java Swing創建響應式界面時,我喜歡將所有計算結果保留在單獨的線程中。

This Oracle Trail is right down your ally.它提供了一個關於提供響應式GUI的完整章節,其中包括後臺任務和線程池。通讀它肯定會解決你的問題。

相關問題