2016-03-15 56 views
0

我有3个类。
ImpAppModel:ArrayList到JList使用MVC

/* 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类(由同伴的NetBeans GUI生成器生成的):

 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类:

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

我有a Error:incopatible types:Object []无法转换为Jlist。问题是(是的,我做了我的研究,我发现的解决方案不适合在MVC模式中使用)如何实现控制器(或修改模型/视图)以使用控制器向array提供arrayList中的元素同时保持MVC模式。
/编辑:我有很大的怀疑,我的问题是由setUser在GUI类的方法引起的,但问题依然如此。

回答

1

A JList包含的形式为ListModel的数据。用setModel()成员定义Jlist的数据。

将数组强制转换为模型对象显然没有意义,但有一个方便的类DefaultListModel可用于将数组导入模型。所以在你的appPanel类中你可以添加

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

这是一种方法,谢谢。 –

0

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

你应该这样做appPanel.setUser(new JList(impAppModel.friendList.toArray()));

或者提供AppPanel类重载setUser(String[] arr)方法,这需要一个数组,并在内部创建JList的对象。