简体   繁体   English

更新JList

[英]Updating an JList

I've now made a JList which is based on an arraylist, and is being filled by the defaultlistmodel. 我现在已经创建了一个基于arraylist的JList,并且由defaultlistmodel填充。 The list will add people when they connect to the server, but it will not show the one connecting, or the ones connecting after. 该列表将在人们连接到服务器时添加人员,但不会显示连接的人或连接后的人。 So, i have to update the JList. 所以,我必须更新JList。

My question is: 我的问题是:

What should i be updating? 我应该更新什么? Is it possible to use a timer which runs the update, or should i implement an updatemethod which runs when someone enters the server? 是否可以使用运行更新的计时器,还是应该实现在有人进入服务器时运行的更新方法?

ps. PS。 This is an chatserver, much like IRC. 这是一个聊天服务器,很像IRC。

Here is some of the code: 以下是一些代码:

The GUI: GUI:

jList2 = new javax.swing.JList();
try{
jList2.setModel(gl.getUsersOnlineAsDefaultListModel(gl.getClients())
    );
}catch(RemoteException ex){
    System.out.println(ex);
}
jScrollPane3.setViewportView(jList2);

The GUI Logic: GUI逻辑:

public DefaultListModel getUsersOnlineAsDefaultListModel(ArrayList<Client> clients) throws RemoteException {
DefaultListModel result = new DefaultListModel();
for(Client c : clients){
    result.addElement(c.findName());
}
    return result;
}

    public ArrayList<Client> getClients() throws RemoteException, NullPointerException{
            return cf.getClients();
    }

The serverside: 服务器端:

ArrayList clients = new ArrayList<Client>();

public ArrayList<Client> getClients(){
    return clients;          
}

What should i be updating? 我应该更新什么?

The list model ( DefaultListModel ) that provides the content of the JList . 列表模型( DefaultListModel ),它提供JList的内容。

Is it possible to use a timer which runs the update, or should i implement an updatemethod which runs when someone enters the server? 是否可以使用运行更新的计时器,还是应该实现在有人进入服务器时运行的更新方法?

The second option sounds better. 第二种选择听起来更好。

我认为最好的方法是实现客户端进入更新JList的服务器触发的侦听器。

Swing is single threaded; Swing是单线程的; you have to accept that all changes to the Swing GUI must be done on the EventDispatchThread , including updates to your XxxListModel . 您必须接受必须在EventDispatchThread上对Swing GUI进行所有更改,包括对XxxListModel更新。 Your code shows RemoteXxx , then you invoke a potentially long running thread from some of Listeners or (as you asked) from Timer . 您的代码显示RemoteXxx ,然后您从一些Listeners或(如您RemoteXxx )从Timer调用可能长时间运行的线程。 Basically you have two choices: 基本上你有两个选择:

1) Implement the required methods of SwingWorker : publish() invoked on the background htread, and process() and `done() invoked on the EDT. 1)实现SwingWorker所需的方法:在后台htread上调用publish() ,在EDT上调用process()和`done()。

2) Wrap execution in a Runnble#Thread , but then all output to the GUI must be wrapped into invokeLater / invokeAndWait , including thread safe methods setText , etc. 2)在Runnble#Thread包装执行,但是所有输出到GUI的必须包装到invokeLater / invokeAndWait ,包括线程安全方法setText等。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM