I have a piece of code I'm working on, I prepared a simple example:
import javax.swing.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
public class Example extends JFrame implements ActionListener {
public static void main(String[] args) {
Example e = new Example();
e.setVisible(true);
}
private JButton button;
public Example() {
this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
this.setSize(600, 400);
this.setLayout(null);
button = new JButton("button");
button.setBounds(200, 150, 200, 50);
button.addActionListener(this);
this.add(button);
}
@Override
public void actionPerformed(ActionEvent actionEvent) {
button.setEnabled(false);
try {
Thread.sleep(5000);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
The pooint is, we have actionPerformed
function, that has two actions: disables the button and runs sleep
to imitate some work that i do.
My problem is that button is being disabled after actionPerformed
ends, so in other words after this 5 seconds of sleep, and I cannot disable it earlier. I've tried to do something with it but so far changing button.setEnabled(false);
to button.setEnabled(false); this.repaint(); this.validate();
does nothing.
My question is: how to do in swing the job, where I need first disable button, then do some time consuming stuff (sleep for example) and enable button when job is done?