Disable button on click before actionPerformed is completed java

Steve picture Steve · Jul 23, 2013 · Viewed 17.6k times · Source

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++) {
                }
            }
        }
    }
});

Answer

trashgod picture trashgod · Jul 23, 2013

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).