Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Disable button on click before actionPerformed is completed java

I have a button doing a long function, I want to disable this button after the user once click on it to in order to prevent him from clicking it again many times

The button gets disabled but the problem is after the function finished the button gets enabled again
i tried to put button.setEnabled(false); in a new thread but it didn't work either

for testing this sample of code

button.addActionListener(new ActionListener() {
    @Override
    public void actionPerformed(ActionEvent ae) {
        button.setEnabled(false);
        for (int i = 0; i < Integer.MAX_VALUE; i++) {
            for (int j = 0; j < Integer.MAX_VALUE; j++) {
                for (int ii = 0; ii < Integer.MAX_VALUE; ii++) {
                }
            }
        }
    }
});
like image 239
Steve Avatar asked Jan 13 '23 20:01

Steve


1 Answers

Use SwingWorker for long running background tasks. In this example, the startButton action does setEnabled(false), and the worker's done() implementation does setEnabled(true).

like image 150
trashgod Avatar answered Jan 31 '23 19:01

trashgod