这是一个垃圾邮件机器人,它会写入一个字符串,当您按下按钮时输入,但是当我按下运行按钮时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();
}
}
这不提供问题的答案。要批评或要求作者澄清,在他们的帖子下留下评论 - 你总是可以评论你自己的帖子,一旦你有足够的[声誉](http://stackoverflow.com/help/whats-reputation),你会能够[评论任何帖子](http://stackoverflow.com/help/privileges/comment)。 – Jubobs 2014-09-24 17:34:53
为什么你认为这不是OPs发布的答案?答案是将他的大多数bot逻辑放在单独的线程中,所以我不明白你在我的评论中看到问题的位置。我不批评他的帖子或他的问题。 – Lemonov 2014-09-24 20:05:53
你可能是对的,但是,作为评论,你的回答会更合适。你可能想详细说明一下。 – Jubobs 2014-09-24 20:10:29