使用 MVC 将 ArrayList 转换为 JList

ArrayList into JList using MVC

我有 3 个 classes.
ImpAppModel:

/* String array for saving members in the friendlist*/
public ArrayList<String> friendList = new ArrayList(10);

/**
 * Method for retrieving elements (added friends) in the array for use in 
 * GUI.
 * @return the elements in the ArrayList
 */
public ArrayList friendList() {
    //method filling the array with 1 testing record
    friendList.add(1, "petr");
    return friendList;
}

我正在查看 appPanel class(由其他 NetBeans GUI Builder 生成):

        Users.setModel(new javax.swing.AbstractListModel() {
        String[] strings = {"User1", "User2", "User3", "User4", "User5"};

        @Override
        public int getSize() {
            return strings.length;
        }

        @Override
        public Object getElementAt(int i) {
            return strings[i];
        }
    });
    /**
 * Method for setting users to display in GUI (variable JList Users)
 * @param user parameter for supplying JList
 */
public void setUser(JList user){
    this.Users = user;
}

最后我控制了 ImpAppContorller class:

private final GuiPanel appPanel;
private final ImpAppModel impAppModel;
/**
 * Main constructor method, creates variables for saving links on Data and 
 * GUI.
 * @param appPanel Ensures communication between GUI panel and controller.
 * @param impAppModel Ensures communication between Model and controller.
 */
public ImpAppController(GuiPanel appPanel, ImpAppModel impAppModel) {

    this.appPanel = appPanel;
    this.impAppModel = impAppModel;

    appPanel.setUser(impAppModel.friendList.toArray());
}

我有一个错误:不兼容的类型:Object[] 无法转换为 Jlist。
问题是(是的,我做了我的研究,我发现的解决方案不适合在 MVC 模式中使用)我如何实现控制器(或修改 model/view)以使用控制器为 JList 提供来自 arrayList 的元素class 同时保持 MVC 模式。
/编辑:我非常怀疑我的问题是由 GUI class 中的 setUser 方法引起的,但问题仍然存在。

appPanel.setUser(JList user) 方法接受类型为 JList 的对象,而在 appPanel.setUser(impAppModel.friendList.toArray()); 中你传递的是数组类型。

你应该做类似 appPanel.setUser(new JList(impAppModel.friendList.toArray()));

或者在 AppPanel class 中提供一个重载的 setUser(String[] arr) 方法,它接受一个数组并在内部创建 JList 对象。

JListListModel. Define the data for your Jlist with the setModel() 成员的形式包含其数据。

将数组转换为 Model 对象显然没有意义,但是可以使用方便的 class DefaultListModel 将数组导入模型。所以在你的 appPanel class 你可以添加

public void setUserData(Object [] data){
    DefaultListModel model = new DefaultListModel();
    model.copyInto(data);
    Users.setModel(model); // Users must exist
}