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

查看:151
本文介绍了通过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 ().

我将不胜感激。

推荐答案

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

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天全站免登陆