jList不显示自定义模型的数据?

时间:2013-04-28 14:03:43

标签: java swing netbeans jlist

我正在尝试通过继承AbstractListModel来填充JList。我已经浏览了很多地方试图找到我做错了什么,但从未设法解决问题。所以这个类处理我的GUI ... < / p>

//View
public class central extends javax.swing.JFrame {

public central() {
    initComponents();
    list.addMouseListener(new abstracts.mouseActions(list));

}

public void setListModel(ListModel l ){
    list.setModel(l);

}

// The rest are auto generated code for the interface, not relevant

那是我的中产阶级......

 public class MainCtrl {
//View reference
private views.central mainFrame = new views.central();
//Model reference
private abstracts.ListData model = new abstracts.ListData();
/*All this was testing purposes and it worked
  private DefaultListModel model = new DefaultListModel();
 */

private void showView(){
    mainFrame.setListModel(model);
    mainFrame.setVisible(true);
    models.contact p2 = new models.contact("Alex", "Christopher","alex@hotmail.com","22","Def");
    models.contact p1 = new models.contact("Joes", "Smith","joey@hotmail.com","33","Def");
    model.addContact(p2);
    model.addContact(p1);
    /* def version
      model.addElement(p2);

    */


}

public static void main(String[] args) {
    try {
        UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
        new MainCtrl().showView();
    }
    catch (Exception e) {
        e.printStackTrace();
    }
}

然后我得到了AbstractListModel实现

public class ListData extends AbstractListModel {    
//Store people info
private Vector<contact> people; 

public ListData() {
    people = new Vector<contact>();
}

public void addContact(contact newPerson){
   people.add(newPerson);
   int per = people.indexOf(newPerson);
   fireIntervalAdded(this,0,getSize());
}

@Override
public contact getElementAt(int index){
    return  people.get(index);
}

@Override
public int getSize(){
    return people.size();
}


@Override
protected void fireIntervalAdded(Object src, int index, int index2){
 System.out.println(index2);    
}

.....

我测试了DefautListModel并显示了值,但是当我合并自定义模型时它不会显示?我缺少一个额外的步骤吗? mainCtrl也是主要类......

谢谢你真的可以使用一些帮助

2 个答案:

答案 0 :(得分:0)

代替

fireIntervalAdded(this,0,getSize());

在您的addContact()中放置

fireContentsChanged(this,0,getSize());

答案 1 :(得分:-1)

 listModel = new DefaultListModel();
 listModel.addElement("Jane Doe");
 listModel.addElement("John Smith");
 listModel.addElement("Kathy Green");


 list = new JList(listModel);

请参阅此链接,它将为您提供帮助

http://docs.oracle.com/javase/tutorial/uiswing/components/list.html