Swing is a single-threaded infrastructure, which means that while the cycle is running, the Dispatcher event flow is blocked and cannot process new events, including redraw requests ...
You need to run your Looper class inside your own thread context. It would also mean that your loop flag should be declared volatile or you should use AtomicBoolean so that it can be checked and changed at the flow boundaries
For instance...
public class Looper implements Runnable { private AtomicBoolean keepRunning; public Looper() { keepRunning = new AtomicBoolean(true); } public void stop() { keepRunning.set(false); } @Override public void run() { while (keepRunning.get()) { System.out.println("aaa"); } } }
Then you could use something like ...
private class thehandler implements ActionListener { private Looper looper; public void actionPerformed(ActionEvent e) { if (e.getSource() == click) { if (looper == null) { looper = new Looper(); Thread t = new Thread(looper); t.start(); } else { looper.stop(); looper = null; } } } }
to run it ...
See Concurrency in Swing and Concurrency in Java for more details.
Also be careful, Swing is not thread safe, you should never create or modify the user interface from the EDT context
source share