Domanda

I created a jList with a custom ListModel to display some objects (User) . I try to use the dao architecture. whene i add a contact to my collection using des DAO class, the Listmodel does not update. it seems that the listmodel is destroyed .

Here is my Jlist with the customListModel.

>    Service dcs = new DefaultService(MyDao);
>    CustomListModel cList = new CustomListModel( dcs );
>    list = new JList<>(cList);
>    list.addMouseListener(new ContactListItemListener(list,this.dcs));

CustomListModel :

public class CustomListModel extends DefaultListModel<Contact>{

    private ContactService dcs ;

    public CustomListModel(ContactService dcs) {
        this.dcs = dcs;
    }

    @Override
    public void addListDataListener(ListDataListener arg0) {
        // TODO Auto-generated method stub

    }
    @Override
    public Contact getElementAt(int i) {
        System.out.println(dcs.list().size()+"  Test "+dcs.list()); //just for testing
        return dcs.list().get(i);

    }

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

    @Override
    public void removeListDataListener(ListDataListener arg0) {
        // TODO Auto-generated method stub

    }

}

and in the ActionPerformed of my listener :

    public void actionPerformed(ActionEvent e) {
        this.dcs.add(new User());
}

When the actionperformed is executed, the new user is added to my list of users, but the customListModel don't display the message of test, it seems that the customListModel is destroyed.

Sorry for my bad english

È stato utile?

Soluzione

The JList doesn't refresh because it has no way to know that something has been added to the database and that it should thus ask the model again for the new elements. You have to fire an event when you add something to the database, or to replace the model of the list by a new model having the fresh list.

BTW, you shouldn't extend DefaultListModel, but AbstractListModel if you don't plan to use the data that DefaultListModel encapsulates. See its fireXxx() method to fire an event.

Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top