java 线程 对话框,Java:如何从另一个线程启动UI对话框,例如用于Authenticator

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.

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. 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.

解决方案

you need SwingUtlities.invokeLater to present the dialog, and a synchronize/notify object to 'pause' and wait for the user to respond.

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

}

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值