Ich erstelle ein einfaches Java-Programm mit einer GUI mit Hilfe von Fenster Builder erstellt. Die GUI besteht nur aus einer Schaltfläche.Java-Thread Start-Stop-Start auf die gleiche Schaltfläche klicken
Starten Sie auf Knopfdruck einen Thread, der bis zur Beendigung der Zufallszahl endlos drucken soll, indem Sie erneut auf die gleiche Schaltfläche klicken.
Hier ist mein Code
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(){
}
}
Vielen Dank im Voraus.
Was ist Ihre Frage? Sie können einen Thread nicht stoppen, indem Sie einfach "Ihre Referenz darauf ersetzen". 'Start' stoppt nie aufgrund der externen (nutzlosen) Schleife. Bitte stellen Sie eine selbsterklärende Frage, möglicherweise eine [mvce]. –