2014-09-24 65 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的完整章节,其中包括后台任务和线程池。通读它肯定会解决你的问题。

相关问题