Java:如何从另一个线程启动UI对话框,例如用于Authenticator [英] Java: How to launch a UI dialog from another thread, e.g. for Authenticator
问题描述
我的问题简单来说:我的GUI应用程序需要执行冗长的网络下载。下载在一个单独的线程中处理。远程站点可能需要身份验证,所以我想定义一个验证器,弹出一个输入用户名和密码对话框。我意识到这个对话框需要从UI线程运行。
My problem in a nutshell: my GUI app needs to execute a lengthy network download. The download is handled in a separate thread. It's possible that the remote site will require authentication, so I want to define an Authenticator that pops up an "enter your username and password" dialog. I realize that this dialog needs to be run from the UI thread.
我相信我不是第一个这样做的人。这是最好的做法是让一个后台线程在UI线程中启动一个对话框,并阻止直到该对话框被关闭?
I'm sure I'm not the first person to do this. What is the best practice here for having a background thread launch a dialog in the UI thread, and block until that dialog is dismissed?
p.s。后台线程非常大,并不仅仅是从网上下载一个文件。换句话说,在这一点上,将它转换为SwingWorker可能不实用,无论如何,我不知道我如何从SwingWorker中解决这个问题。
p.s. the background thread is very large and does a lot more than just download a file from the net. In other words, it's probably not practical at this point to convert it to a SwingWorker, and anyway, I'm not sure how I would solve this from a SwingWorker either.
推荐答案
你需要 SwingUtlities.invokeLater 显示对话框,同步/通知对象暂停并等待用户响应。
you need SwingUtlities.invokeLater to present the dialog, and a synchronize/notify object to 'pause' and wait for the user to respond.
基本上在你的工作(非gui)线程:
Basically in your worker(non-gui) thread:
final Object obj = new Object() ; // or something to receive your dialog's answer(s)
Runnable r = new Runnable() {
void run() {
Dialog d = new Dialog() ;
Button b = new JButton("ok") ;
b.addActionListener(new ActionListener() {
void actionPerformed(ActionEvent e) {
synchronize(obj) { // can lock when worker thread releases with wait
obj.notify() ; // signals wait
}
}
}) ;
}
} ;
synchronize( obj ) {
SwingUtilites.invokeLater(r) ; // executs r's run method on the swing thread
obj.wait() ; // releases obj until worker thread notifies
}
这篇关于Java:如何从另一个线程启动UI对话框,例如用于Authenticator的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!