问题
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++) {
}
}
}
}
});
回答1:
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).
回答2:
everything wrapped in
public void actionPerformed(ActionEvent ae) {is done at one moment, (on the screen) when all code lines are executed, this is basic rule for AWT/Swing Listeners and EventDispatchThreadyou need to delay event in EDT by using
- short delay with Swing Timer,
- redirect rest of code (after
button.setEnabled(false);) toSwingWorker, easiest toRunnable#Thread, note all output fromRunnable#Threadto the already visible Swing GUI must be wrapped intoinvokeLater
proper of ways will be only using
Swing Actionand instead of locking theJButtonto setAction.setEnabled(false)only
回答3:
Edit: It's tempting to think you could use a mouse listener to implement this. For example, to prevent you could use mouse released event or mouse clicked event of mouse listener. Inside that you could write button.setEnable(false). Unfortunately, this also blocks the event dispatch thread.
来源:https://stackoverflow.com/questions/17807846/disable-button-on-click-before-actionperformed-is-completed-java