I've got this programme of computing prime numbers. When pressing stop the programme stops computing the prime numbers but when I press GO i need the programme to continue with its computations, but I couldn't find out how can I start my thread again. I tried creating new instances of it but nothing happened. Here's my code:
public class PrimeApp1 extends JFrame {
protected JTextArea output;
protected JButton go;
protected JButton stop;
protected long counter = 2;
protected boolean stopComputation = false;
public boolean run = true;
protected boolean isPrime(long number) {
long max = (long) Math.sqrt(number) + 1;
for (long i = 2; i < max; i++) {
if ((number % i) == 0) {
return (false);
}
}
return (true);
}
public class PrintPrimes extends Thread {
@Override
public void run() {
// TODO Auto-generated method stub
int primecount = 0;
while (run == true) {
if (isPrime(counter)) {
primecount++;
output.append(Long.toString(counter) + "\n");
stop.setEnabled(true);
}
counter++;
}
}
}
public PrimeApp1() {
super("Prime Numbers");
final PrintPrimes print = new PrintPrimes();
JPanel content = new JPanel();
BorderLayout contentLayout = new BorderLayout();
content.setLayout(contentLayout);
output = new JTextArea();
output.setEditable(false);
JScrollPane scroller = new JScrollPane(output);
content.add(scroller, BorderLayout.CENTER);
JPanel buttonPane = new JPanel();
FlowLayout buttonPaneLayout = new FlowLayout();
buttonPane.setLayout(buttonPaneLayout);
go = new JButton("Go");
stop = new JButton("Stop");
stop.setEnabled(false);
buttonPane.add(go);
buttonPane.add(stop);
content.add(buttonPane, BorderLayout.SOUTH);
go.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
print.start();
}
});
stop.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
run = false;
}
});
setContentPane(content);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setSize(600, 600);
setVisible(true);
}
public static void main(String[] args) {
new PrimeApp1();
}
}