Seinfeld
Seinfeld

Reputation: 433

How to change DeafultListModel with ArrayList in Java Eclipse

I'm building a chat room, but now I have a problem with adding users to a list and using it to render user names aside of program (so everyone can see who's connected to a chat at that moment).

Actually, I have no problem with that when I'm using DeafultListModel and it looks like this

 public void updateUsers(Vector v)
   {
      DefaultListModel<String> listModel = new DefaultListModel();
      if (v != null)
         for (int i = 0; i < v.size(); i++)
         {

            try
            {
               String tmp = ((ChatClientInt) v.get(i)).getName();
               listModel.addElement(tmp);
            }
            catch (Exception e)
            {
               e.printStackTrace();
            }

         }
      lst.setModel(listModel);
   }

This one works.

However, I have problem when trying to replace Vector with ArrayList. I'm not sure how to replace the last line of code.

lst.setModel(listModel);

This is my ArrayList attempt:

   public void updateUsers(ArrayList<ChatClientInterface> v)
   {
      ArrayList<String> listModel = new ArrayList<String>();
      if (v != null)
         for (int i = 0; i < v.size(); i++)
         {

            try
            {
               String tmp = ((ChatClientInterface) v.get(i)).getName();
               listModel.add(tmp);
            }
            catch (Exception e)
            {
               e.printStackTrace();
            }

         }

   }

Upvotes: 0

Views: 112

Answers (1)

Bajal
Bajal

Reputation: 6016

JList.setModel() expects an implementation of ListModel. So you have to keep the listModel object as type DefaultListModel. See: https://docs.oracle.com/javase/7/docs/api/javax/swing/JList.html#setModel(javax.swing.ListModel)

public void updateUsers(ArrayList<ChatClientInterface> v)
 {
   DefaultListModel<String> listModel = new DefaultListModel();
  if (v != null)
     for (int i = 0; i < v.size(); i++)
     {

        try
        {
           String tmp = ((ChatClientInterface) v.get(i)).getName();
           listModel.addElement(tmp);
        }
        catch (Exception e)
        {
           e.printStackTrace();
        }

     }
  lst.setModel(listModel);
}

Upvotes: 2

Related Questions