锁定JButton以防止多个SwingWorkers

时间:2014-04-24 10:43:00

标签: java swing jbutton swingworker

我似乎无法找到一种方法来防止双击时调用SwingWorker两次。

问题是,只需将JButton设置为setEnabled(false),就不会阻止某人快速双击以多次运行它。

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

2 个答案:

答案 0 :(得分:3)

不要使用MouseListener按钮,您应该使用ActionListener

有关详细信息,请参阅How to Use Buttons, Check Boxes, and Radio ButtonsHow to Write an Action Listener

答案 1 :(得分:1)

使用ActionListener而不是MouseListener

为什么使用ActionListener,ActionListener用于处理按钮的逻辑单击。 点击发生

- when the mouse is pressed then released on a button,
- when the keyboard shortcut of that button is used,
- when the button has the focus and the space bar is pressed,
- when the button is the default button and Enter is pressed,
- when the button's click() method is called programmatically


 A MouseListener only handles low-level mouse events.