How can components work concurrently in JFrame?

83 Views Asked by At

code:

button.addActionListener(new ActionListener() {
    public void actionPerformed(ActionEvent e) {
        textArea_output.append(new Date() + ": start\n");
        try {
            Thread.sleep(5000);
        } catch (InterruptedException e2) {
            e2.printStackTrace();
        }
        textArea_output.append(new Date() + ": end");
    }
});

output:

Sat Nov 30 14:46:08 CST 2013: start
Sat Nov 30 14:46:13 CST 2013: end

The problem is that the two outputs appear at the same time. And what I want is, the first one, 5 seconds, then another.

I tried several ways to solve it but all failed. The button just froze the whole frame, even the textArea won't update its content during the time.

2

There are 2 best solutions below

0
On

This page helps. Just Simply starts a new Thread. (I tried this but I don't know why it didn't work that time.

5
On

Don't block the EDT (Event Dispatch Thread) - the GUI will 'freeze' when that happens. Instead of calling Thread.sleep(n) implement a Swing Timer for repeating tasks, or a single shot Timer for a 'delayed effect'.

See Concurrency in Swing for more details.