Swing GUI 未更新 [英] Swing GUI is not updating

查看:38
本文介绍了Swing GUI 未更新的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个简单的 Java Swing 应用程序,它使用 zip4j 来加密和解压 zip 文件.是由这部分代码完成的:

I have simple Java Swing application which uses zip4j to encrypt and unpack zip file. It's done by this part of code:

ZipFile zipFile = new ZipFile("dataStorage.zip");
zipFile.setPassword(password);
zipFile.setRunInThread(true);
ProgressMonitor progressMonitor = zipFile.getProgressMonitor();
if (!verify(zipFile)) {
    JOptionPane.showMessageDialog(null, "You have entered incorrect password!", "ERROR", 0);
    return;
}
zipFile.extractAll("./"); //runs in new thread
//After entering this while GUI freezes
while (progressMonitor.getState() == ProgressMonitor.STATE_BUSY) {
    System.out.print("."); // this works normally...
    try {
        Thread.sleep(1000);
    } catch (InterruptedException ex) {
    //
    }
    pbEncryptionProgress.setValue(progressMonitor.getPercentDone()); //this is not updating progress bar, but getPercentDone is returning correct data
}

问题是进度条没有更新.应用程序 GUI 似乎冻结了.但是,点正在打印到控制台.如何修复它以更新进度条?

Problem is that progress bar is not being updated. Application GUI seems frozen. However, dots are being printed to console. How can I fix it to update that progress bar?

推荐答案

请阅读并发在摆动.

您正在做的是通过休眠和更新来耗尽 EDT 的所有资源,而不是留出任何时间实际重绘您的 GUI.EDT 适用于 GUI 上的小型操作.您应该永远在 EDT 上调用 Thread.sleep().

What you are doing is using up all resources of the EDT by sleeping and updating, not leaving any time for it to actually redraw your GUI. The EDT is meant for small operations on the GUI. You should never call Thread.sleep() on the EDT.

您可以做的是制作一个 Timer,它会每秒运行一次您的支票,直到支票通过.这样 EDT 就可以自由地不冻结.

What you could do is make a Timer that would run your check every second until the check passes. That way the EDT would be free to not freeze.

一个更好的方法是使用SwingWorker.它有做你特定事情的方法:

A much better way of doing this is by using a SwingWorker. It has methods that do your specific thing:

  • 要在后台执行的任务(在您的情况下 - 解压缩)
  • 一种将部分结果发布到 GUI 的方法(在您的情况下完成百分比)
  • 对部分结果做出反应的方法(在您的情况下 - 更新进度)
  • 完成后调用的方法(在您的案例中未显示,但无论如何都很有用).

这篇关于Swing GUI 未更新的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆