Java wait for JFrame to finish

佐手、 提交于 2019-12-29 08:11:41

问题


I have a login frame that i have to wait for from another thread. Upon successful login frame disposes itself. And i want to pop up the main frame for the application. Right now i am watching a boolean value to determine when to fire up the main frame. What is the correct way of doing this? Watching a boolean value just does not feel elegant.


回答1:


If you have Java 5 or later available, you could use a CountDownLatch. For example, assuming the main frame is in control initially, have the main frame create the CountDownLatch with a count down of 1 and pass this latch to the login frame. Then have the main frame wait for the latch to become 0:

CountDownLatch loginSignal = new CountDownLatch(1);
     ...    // Initialize login frame, giving it loginSignal 
     ...    // execute login frame in another Thread
// This await() will block until we are logged in:
loginSignal.await();

Have the login frame, when done, decrement the Latch:

loginSignal.countDown();

Ensure that there is no way for your login frame to exit where it forgets to decrement the latch! As soon as the CountDownLatch reaches 0, the main frame becomes runnable.

You could also use a Semaphore or Condition (or any of a few other choices from java.util.concurrent), but for this purpose, a CountDownLatch seems easier to use.




回答2:


What you really must understand with dealing with Swing (and in fact AWT), is that you need to keep all interaction with the components of the AWT Event Dispatch Thread (EDT).

So, do the login off the EDT. Use a new Thread, or better a java.util.concurrent.ExecutorService. When you discover that you have been logged in, use java.awt.EventQueue.invokeLater to get back onto the EDT. Anonymous inner class are great for capturing context and, despite their horrendously verbose syntax, making the code shorter.



来源:https://stackoverflow.com/questions/799631/java-wait-for-jframe-to-finish

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!