Java Swing stabilization mechanism

Source: Internet
Author: User

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

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.