Start with the question.
Our product's operating platform (Workbench) is a Java swing program. There is an event handler code as follows:
Public void actionperformed (ActionEvent e) { // do time-consuming work, such as inserting a database }
One problem now is that if the user points to the button two times, the event handler is executed two times, then the user gets a primary key repeat error.
The simple idea is to give disable/enable the corresponding OK button at the beginning of the event handler.
Public void actionperformed (ActionEvent e) { try { // Disable OK button ... // do time-consuming work finally { // enable OK button ... }}
But the above code is wrong.
Event Dispatch Thread Workflow:
Enter handling code of EVENT1, disable button, and enable button, enter handling code of EVENT2
The right implementation:
public void actionperformed (ActionEvent e) { try " Span style= "color: #000000;" > { // disable OK button ... // Doing time-consuming work } finally {Swingutilities.invokelater ( new Runnable () {@Override public void run () { // enable OK button ...
Event Dispatch Thread Workflow:
Enter handling code of EVENT1, disable button, ignore Event2, enable button
If Invokelater is called from the event dispatching thread--for example, from a JButton ' s ActionListener--the Doru N.run () would still is deferred until all pending events has been processed.
References
https://docs.oracle.com/javase/tutorial/uiswing/concurrency/
Https://docs.oracle.com/javase/7/docs/api/javax/swing/SwingUtilities.html#invokeLater (java.lang.Runnable)
Java Swing stabilization mechanism