简体   繁体   English

将字符串ArrayList绑定到JList

[英]Binding String ArrayList to JList

I have created a client -> server chat room system, and I have a list of currently connected users, which is currently displayed on a button click within a JTextField, this currently works fine and displays the string array. 我创建了一个客户端->服务器聊天室系统,并且有一个当前连接的用户列表,该列表当前显示在JTextField中的按钮单击上,目前可以正常工作并显示字符串数组。 However, I have added another component to my GUI, being a JList. 但是,我在GUI中添加了另一个组件,即JList。 I have been trying to create a method called updateUserList to update the JList with the users that are connected. 我一直在尝试创建一种名为updateUserList的方法,以使用连接的用户更新JList。 I have tried to use a DefaultListModel of type String, however this displays nothing in the JList and I am unsure as to why. 我尝试使用String类型的DefaultListModel,但是在JList中什么也不显示,我不确定为什么。

Below is the updateUserList method I have created: 下面是我创建的updateUserList方法:

public void updateUserList()
{
    model = new DefaultListModel<String>();
    for(String usernames : users)
        model.addElement(usernames);
    jl_users = new JList<String>(model);
}

Please note that model, usernames and jl_users are defined globally, therefore I have not included them in the post. 请注意,模型,用户名和jl_users是全局定义的,因此我没有在帖子中包含它们。

Why are you using DefaultListModel ? 为什么使用DefaultListModel If you want a simply List just use it like this 如果您只需要一个列表,请像这样使用它

public void updateUserList()
{
  jl_users = new JList<String>(users.toArray(new String[users.size()]));
}

or straight forward 或直接

 jl_users = new JList(users.toArray());

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

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