2

我正在尝试通过对 AbstractListModel 进行子类化来填充 JList。我已经查看了许多地方以尝试找出我做错了什么,但从未设法解决问题。所以这个类处理我的 GUI ......

//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 也是主类...

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

4

2 回答 2

0

代替

fireIntervalAdded(this,0,getSize());

在你的 addContact() 放

fireContentsChanged(this,0,getSize());

于 2019-05-27T02:04:11.867 回答
-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

于 2013-04-28T14:13:03.107 回答