I am developing a java swing desktop application. The dialog form has an ok and cancel button. When the user clicks ok button the application does some processing. How can I stop user from clicking ok again before the event on ok button has finished executing. Also, i dont want the user to able to press the cancel button till ok has finished executed. Any help will be highly appreciated.
5 Answers
Enablement management is an integral part of UI logic. Action helps you doing so:
Action action = new AbstractAction("myAction") {
public void actionPerformed(ActionEvent e) {
setEnabled(false);
doPerform();
setEnabled(true);
}
};
button.setAction(action);
Beware: long running task must not be executed on the EDT, so this is for short-term only, to prevent the second or so click having an effect
Edit
just noticed that you tagged the question with jsr296, then it's even easier: you can tag a method of your presentation model as @Action and bind its enabled property to a property of the model
@Action (enabledProperty == "idle")
public void processOk() {
setIdle(false);
doStuff;
setIdle(true);
}
Plus there is support (much debated, but useable) for Tasks: basically SwingWorker with fine-grained beanified life-cycle support

- 51,061
- 28
- 99
- 211
If you want to disable all the controls, then I'd suggest using a GlassPane
. See here for more info: http://docs.oracle.com/javase/tutorial/uiswing/components/rootpane.html

- 4,315
- 1
- 27
- 33
The easiest way is to disable the button just after clicking it , and when the action performed is complete then re-enable it.

- 18,213
- 29
- 88
- 158
-
But what is the case when there are many buttons on my dialog, i will have to continuously enable and disable and it might become a maintenance nightmare. There should be a more graceful way to do it. – Will Nov 15 '11 at 08:41
You can disable your button like yourButton.setEnabled(false); during your processing method and enable it again when it finishes.

- 26,874
- 17
- 90
- 115
-
-
actually .. no, don't fiddle with button state directly, instead configure it with an Action and do the state management there – kleopatra Nov 15 '11 at 09:14