由java中的另一个线程刷新GUI(swing) [英] Refreshing GUI by another thread in java (swing)

查看:38
本文介绍了由java中的另一个线程刷新GUI(swing)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个主程序,其中 GUI 基于 Swing 并且根据四种状态之一,GUI 元素具有不同的参数.

I have a main program, in which GUI is based on swing and depending on one of four states the GUI elements have different parameters.

public class Frame extends JFrame implements Runnable {
Status status = 1;
...
@Override
public void run() {
    switch (status) {
        case 1:
        ...
        case 2:
        ...
}

public void updateGUI(Status status) {
   this.status = status;
   SwingUtilities.invokeLater(this);
}

如果我想刷新 GUI 只调用具有适当参数的 updateGUI,一切都很好.但该程序还创建了一个额外的线程,该线程在处理相关数据后应更改 GUI 主程序.不幸的是我不能在这个线程中调用 updateGUI (..) 方法.

And if I want to refresh the GUI invokes only updateGUI with appropriate parameter, and everything is fine. But the program also creates an additional thread, which after processing the relevant data should change the GUI main program. Unfortunately I can not in this thread call the method updateGUI (..).

我知道我可以使用 invokeLater 或 SwingWorker 来刷新,但有 10 多个元素,所以我宁愿使用方法 udpateGUI ().

I know that I can use invokeLater or SwingWorker to refresh but there are more than 10 elements so I would rather use the method udpateGUI ().

如有任何提示,我将不胜感激.

I will be grateful for any hint.

推荐答案

如果你使 status 字段线程安全,那么你可以直接从你的后台线程调用 setStatus.为了使状态线程安全,请将更改放入同步块中,并使变量可变,以便其他线程上的更新可见.

If you make the status field thread safe, then you can call setStatus directly from your background thread. To make the status thread-safe, put changes in a synchronize block, and make the variable volatile so updates on other threads become visible.

例如

public class Frame extends JFrame implements Runnable {
private volatile Status status = 1;
...
@Override
public void run() {
    switch (status) {
        case 1:
        ...
        case 2:
        ...
}

public void updateGUI(Status status) {
   setStatus(status);
   SwingUtilities.invokeLater(this);
}

private synchronized void setStatus(Status status) {
   this.status = status;
}

有了这些更改,就可以从任何线程调用 setStatus.

With these changes in place, it's ok to call setStatus from any thread.

这篇关于由java中的另一个线程刷新GUI(swing)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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