简体   繁体   English

Java等待JFrame完成

[英]Java wait for JFrame to finish

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. 看一个布尔值只是感觉不优雅。

If you have Java 5 or later available, you could use a CountDownLatch . 如果您有Java 5或更高版本,则可以使用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. 例如,假设主帧最初处于控制状态,请让主帧创建CountDownLatch ,倒数为1,并将此锁存器传递给登录帧。 Then have the main frame wait for the latch to become 0: 然后让主框架等待锁存器变为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: 完成登录框后,减少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. 一旦CountDownLatch达到0,主框架就会变为可运行。

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. 您也可以使用SemaphoreCondition (或java.util.concurrent任何其他选项),但为此, CountDownLatch似乎更容易使用。

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). 处理Swing(实际上是AWT)时你真正必须理解的是,你需要保持与AWT事件调度线程(EDT)组件的所有交互。

So, do the login off the EDT. 所以,从EDT登录。 Use a new Thread , or better a java.util.concurrent.ExecutorService . 使用new Thread ,或者更好的java.util.concurrent.ExecutorService When you discover that you have been logged in, use java.awt.EventQueue.invokeLater to get back onto the EDT. 当您发现已登录时,请使用java.awt.EventQueue.invokeLater返回EDT。 Anonymous inner class are great for capturing context and, despite their horrendously verbose syntax, making the code shorter. 匿名内部类非常适合捕获上下文,尽管它们的语法非常冗长,但使代码更短。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM