如何在SwingWorker中构造publish()和process()以更新EDT上的多个Swing组件? [英] How to structure publish() and process() in a SwingWorker to update more than one Swing component on the EDT?

查看:105
本文介绍了如何在SwingWorker中构造publish()和process()以更新EDT上的多个Swing组件?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在SwingWorker中有一个ServerSocketChannel连接过程.在Swing应用程序本身中,两个JLabel应该更新为(1)一个String(连接状态)和(2)一个int(已连接的客户端数量).下面是检测客户端" JButton运行连接过程之前的应用程序的屏幕截图.但是,我不确定如何在EDT上更新publish()和process()以更新多个Swing组件.有人对如何实现这一目标有指导吗?

I have a ServerSocketChannel connection process in a SwingWorker. In the Swing application itself, two JLabels should update with (1) a String (connection status) and (2) an int (# of clients connected). Below is a screenshot of the application before "Detect Clients" JButton runs the connection process. However, I am not sure how to publish() and process() so as to update more than one Swing component on the EDT. Does anyone have guidance on how to achieve this?

因为List<V>是process()的参数,所以我尝试<Object>作为<V>.但是,这似乎遇到了从字符串/整数到对象的转换问题,反之亦然.

Because List<V> is the parameter of process(), I tried <Object> as <V>. However, this seems to run into issues of conversion from Strings/ints to Objects, and then vice versa.

下面的演示代码说明了应发布更新的几个点:

The below demo code illustrates several points where updates should be published:

protected Void doInBackground() {
    try {
       // Omitted: obtain selector
       ServerSocketChannel ssc = ServerSocketChannel.open() // could fail, may need
       // to publish status
       ssc.socket().bind(serverAddress); // could fail, may need to publish status
       ssc.configureBlocking(false); // could fail, may need to publish status
       // Omitted: register ssc
       while (true) {
           int count = sel.select(1000); // may need to publish for # of clients
           // Omitted: rest of processing     
       }
    } catch (IOException e) {
        //handle error
    } 
}

推荐答案

嗯,现在我明白了您的问题.您正在尝试发布2种不同的信息.请注意,传递给process()方法的List可能包含 multiple publish()调用的结果,因此传递不同类型的值将在您的process()方法中造成混淆.相反,您应该创建一个简单的对象来封装要传递的状态的 all ,并始终发布该类的实例(这也将解决所有转换问题).例如:

Ah, now i understand your problem. you are trying to publish 2 different bits of information. note that the List passed into the process() method could contain the results of multiple publish() calls, so passing different types of values will get confused in your process() method. instead, you should create a simple object to encapsulate all of the state you wish to pass, and always publish instances of that class (which will also solve all of your casting issues). e.g.:

public class ChannelStatus {
  public final boolean active;
  public final int numClients;
}

然后,您将始终发布具有当前客户端数量和活动"状态的ChannelStatus实例.

Then, you would always publish a ChannelStatus instance with the current number of clients and "active" status.

这篇关于如何在SwingWorker中构造publish()和process()以更新EDT上的多个Swing组件?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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