這是一個垃圾郵件機器人,它會寫入一個字符串,當您按下按鈕時輸入,但是當我按下運行按鈕時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