sindrem
sindrem

Reputation: 1231

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;          
}

Upvotes: 3

Views: 925

Answers (3)

mKorbel
mKorbel

Reputation: 109823

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.

Upvotes: 3

Alanmars
Alanmars

Reputation: 1277

I think the best way to do that is implementing a listener fired by the event the client enters the server which updates the JList.

Upvotes: 3

Bhesh Gurung
Bhesh Gurung

Reputation: 51030

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.

Upvotes: 3

Related Questions