【问题标题】:How to change DeafultListModel with ArrayList in Java Eclipse如何在 Java Eclipse 中使用 ArrayList 更改 DeafultListModel
【发布时间】:2016-09-16 19:05:22
【问题描述】:

我正在构建一个聊天室,但现在我在将用户添加到列表并使用它在程序之外呈现用户名时遇到了问题(这样每个人都可以看到当时谁连接到聊天)。

其实我在使用DeafultListModel时没有问题,看起来像这样

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

这个有效。

但是,我在尝试用 ArrayList 替换 Vector 时遇到问题。我不确定如何替换最后一行代码。

lst.setModel(listModel);

这是我的 ArrayList 尝试:

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

         }

   }

【问题讨论】:

  • 不知道为什么要更改 listModel 的类型。我认为应该保留DefaultListModel&lt;String&gt; listModel
  • 学校项目。我无法使用向量
  • 是的,那部分很好。我的评论是关于listModel。请参阅下面的我的答案,该答案已编译。希望我正确理解了您的问题。

标签: java eclipse swing arraylist jlist


【解决方案1】:

JList.setModel() 需要 ListModel 的实现。因此,您必须将 listModel 对象保留为 DefaultListModel 类型。 见: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);
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2012-09-28
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-03-16
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多