Search code examples
javaswingjbuttonswingworker

Locking JButton to prevent multiple SwingWorkers


I cant seem to find a way to prevent a SwingWorker from being called twice on a double click.

The issue is that simply setting the JButton to setEnabled(false) doesn't prevent someone from double clicking fast enough to run it more than once.

startButton.addMouseListener(new MouseAdapter() {
    @Override
    public void mouseReleased(MouseEvent arg0) {
        makeItSo();
    }
});

private void makeItSo () {
    startButton.setEnabled(false);
    myWorker myW = new myWorker();
    myW.execute(); // Executes allot of work. But errors if this is running more than once.
}

Solution

  • Don't use a MouseListener for buttons, you should be using an ActionListener

    See How to Use Buttons, Check Boxes, and Radio Buttons and How to Write an Action Listener for more details