从Java中的另一个线程更新JTextField [英] Update JTextField from another thread in Java

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

问题描述

我正在制作一个游戏客户端/服务器,我正在新的线程更新客户端GUI上的一些信息(使用Swing)。我正在尝试使用SwingUtilities但它不起作用。另外,我听说SwingUtilities每次使用它时都会创建一个新线程,所以我也在寻找一种新方法(我有10个左右的JTextFields需要更新)。有没有办法不使用SwingUtilities?这就是我现在所拥有的。

I'm making a game client/server and I'm having a new thread update some info on the client GUI (which is using Swing). I'm trying to use SwingUtilities but it's not working. Also, I heard SwingUtilities creates a new thread everytime you use it so I'm looking for a new way as well (I have 10 or so JTextFields to be updated). Is there a way to do it without using SwingUtilities? Here is what I have right now.

SwingUtilities.invokeLater(    
        new Runnable() {    
           public void run()    
           {    
              Client.status.setText("status = "+status); 
           }    
        });


推荐答案

我不知道你在哪里听说过 SwingUtilities创建了一个新的线程,但我认为您已经误解或被错误地通知了。 SwingUtilities.invokeLater Runnable 放在Event Dispatcher队列的末尾。然后队列在它自己的线程上下文(及时)内处理此事件,调用运行,没有为此进程创建新线程。

I don't know where you heard about "SwingUtilities creates a new thread" from, but I think you've either misunderstood or being informed incorrectly. SwingUtilities.invokeLater places the Runnable onto the end of the Event Dispatcher's queue. The queue then processes this event within the it's own thread context (in time), calling Run, there is no "new" thread created for this process.

关于你的问题。

您可能需要致电 validate()(以及可能 repaint())字段父容器以鼓励它更新;)

You may need to call validate() (and possibly repaint()) on the fields parent container to encourage it update ;)

不,没有任何其他方法可以跨线程同步UI,这就是 SwingUtilities

And no, there isn't any other way to sync the UI across threads, that's the reason for SwingUtilities

这篇关于从Java中的另一个线程更新JTextField的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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