How to add listener event to JList elements which are added by DefaultListModel object?

event-handling, java, jlist, listselectionlistener, swing

Solution

In following way i've added elements to addGroupList

model1.addElement(arrayList1.get(arrayList1.size()-1));

No you haven't. `model1` is the list model for `addApkList` not `addGroupList`:

 addApkList = new JList(model1);

It should be `model2.addElement(arrayList1.get(arrayList1.size()-1))`.

In any case I suspect you're expecting for a ListSelectionEvent being fired when you just simply add an item to list model. That won't happen. You need to set the added item as the selected one:

Object item = arrayList1.get(arrayList1.size()-1);
model2.addElement(item);
addGroupList.setSelectedValue(item, true);

Take a look to JList.setSelectedValue(Object anObject, boolean shouldScroll) for further details.

Problem

I have created 2 JLists 'addGroupList' and 'addApkList'. I am adding elements to addGroupList using model.addElement(arrayList1.get(arrayList1.size()-1)); the thing is, I want to update addApkList based on selected value of addGroupList. For this, I'm trying to add event listener so that I can act upon something when list item is selected but the event is not trigerring. What do I do to accomplish this? following is the code I'm using. ``` model1 = new DefaultListModel(); model2 = new DefaultListModel(); addApkList = new JList(model1); addGroupList = new JList(model2); scrollPane1 = new JScrollPane(); scrollPane1.setViewportView(addApkList); scrollPane2 = new JScrollPane(); scrollPane2.setViewportView(addGroupList); ``` this way i've defined JList. in following way i've added elements to addGroupList ``` model1.addElement(arrayList1.get(arrayList1.size()-1)); ``` and in following way I've added listener to it. ``` addGroupList.addListSelectionListener(new ListSelectionListener() { @Override public void valueChanged(ListSelectionEvent lse) { if (!lse.getValueIsAdjusting()) { System.out.println("Selection trigerred"); } } }); ``` There doesnt seem to happen any change with this code. what m i doing wrong? I've also tried following ``` model1.addListDataListener(new ListDataListener() { @Override public void intervalAdded(ListDataEvent lde) { System.out.println("ddddddddddd"); throw new UnsupportedOperationException("Not supported yet."); //To change body of generated methods, choose Tools | Templates. } @Override public void intervalRemoved(ListDataEvent lde) { System.out.println("ddddddddddd"); throw new UnsupportedOperationException("Not supported yet."); //To change body of generated methods, choose Tools | Templates. } @Override public void contentsChanged(ListDataEvent lde) { System.out.println("ddddddddddd"); throw new UnsupportedOperationException("Not supported yet."); //To change body of generated methods, choose Tools | Templates. } }); ```

Original source