2016-03-15 57 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的對象。