java gui 去掉按钮_JAVA GUI关闭按钮不起作用(用SwingWorker解决)

本文介绍了JAVA GUI程序中关闭按钮失效的原因,主要是由于在Event Dispatch Thread(EDT)上执行了耗时操作导致。解决办法是通过SwingWorker将耗时的写文件操作移至后台线程。创建一个继承SwingWorker的类,在doInBackground()方法中执行写文件任务,然后在按钮监听器中启动SwingWorker实例。应用此方法后,点击关闭按钮时线程不再被阻塞。
摘要由CSDN通过智能技术生成

最近写了两个GUI小程序,都是和写文件有关的。但是都发现,每次程序运行起来,关闭按钮就不起作用。上了“爆栈”网站和CSDN发了帖,爆栈给出的原因如下,有需要翻译的请留言。

The EDT(Event Dispatch Thread) is responsible for (amongst other things) processing all the UI events that occur, including the request to close your window. But if you block this thread with time consuming tasks (like I/O, loops, Thread#sleep or any other blocking operation), then the EDT is unable to process any of the events accumulating in the queue.

In this case, you best bet would be to use a SwingWorker to off load the writing of the file to another thread. Check out Concurrency in Swing for more information

具体是因为我的写文件操作是在一个button的listener里面触发的,导致读文件操作没完成的时候,线程阻塞了。可以看到按钮是不会反弹回来的。所以再点关闭按钮也就没返回了。

具体解决方法就是要写一个类,继承SwingWorker 类,重写doInBackground()方法,把耗时的写文件操作写在这个方法里面。然后在button的listener里面创建SwingWorker实例,并调用它的execute()方法,即会调用到我们重写的doInBackground()方法

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值