我似乎无法找到一种方法来防止双击时调用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.
}
答案 0 :(得分:3)
不要使用MouseListener
按钮,您应该使用ActionListener
有关详细信息,请参阅How to Use Buttons, Check Boxes, and Radio Buttons和How 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.