0
我正在用窗口構建器的幫助下構建的GUI創建一個簡單的java程序。 GUI由一個按鈕組成。Java線程啓動 - 停止 - 在同一個按鈕上點擊開始
點擊按鈕後,啓動一個線程,該線程將無限次地打印到隨機數,直到再次單擊相同的按鈕而停止爲止。
這裏是我的代碼
LoopTest.java
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
public class LoopTest extends JFrame implements ActionListener {//******
private JButton startB, stopB;
private JTextArea oa;
Start sta;
public LoopTest(){
super("Final Exam: Question ");
Container c = getContentPane();
c.setLayout(new FlowLayout());
startB = new JButton("START"); c.add(startB);
stopB = new JButton("STOP"); c.add(stopB);
oa = new JTextArea(5,20); c.add(oa);
c.add(new JScrollPane(oa));
registerEvents();
sta = new Start("Loop", oa);
}
public void registerEvents(){
startB.addActionListener(
new ActionListener(){
public void actionPerformed(ActionEvent ae){
if(startB.isEnabled() == true)
sta.setLoopFlag(true);
if(!sta.isAlive())
sta.start();
startB.setEnabled(false);
}
}
);
stopB.addActionListener(
new ActionListener(){
public void actionPerformed(ActionEvent ae){
if(stopB.isEnabled()==true){
sta.setLoopFlag(false);
}
}
}
);
}
@Override
public void actionPerformed(ActionEvent e) {
// TODO Auto-generated method stub
}
public static void main(String[] args){
LoopTest app = new LoopTest();
app.setSize(300,300);
app.setLocationRelativeTo(null);
app.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
app.setVisible(true);
}
}
Start.java
public class Start extends Thread {
private JTextArea ta;
private boolean loopFlag;
public Start(String name, JTextArea ta){
super(name);
this.ta = ta;
ta.setText("");
loopFlag = true;
}
public void run(){
int num=0;
while(true)
while(loopFlag){
num = 1+ (int)(Math.random()*100);
ta.append(num + "\n");
}
}
public void setLoopFlag(boolean value){
loopFlag = value;
}
}
Stop.java
public class Stop extends Thread {
public Stop(String name){
super(name);
}
public void run(){
}
}
在此先感謝。
什麼是你的問題?您無法通過簡單地「替換您的引用」來阻止該線程。由於外部(無用)循環,「開始」永遠不會停止。請提出一個不言自明的問題,可能是[mvce]。 –