简体   繁体   中英

Updating an JList

I've now made a JList which is based on an arraylist, and is being filled by the 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.

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. This is an chatserver, much like IRC.

Here is some of the code:

The 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:

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 .

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; you have to accept that all changes to the Swing GUI must be done on the EventDispatchThread , including updates to your XxxListModel . Your code shows RemoteXxx , then you invoke a potentially long running thread from some of Listeners or (as you asked) from 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.

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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