Question

I have this bug, after populating the JList, I try to retrieve the value of the selected item. But when I am doing it, it is called twice.

Here is my code :

 public CaveAdventureUI(CaveGame game) {
    initComponents();
    playerCarryItemModel = new DefaultListModel();
    caveCarryItemModel = new DefaultListModel();
    this.caveGame = game;
    this.world = game.getCaveWorld();
    listSelectionModel = this.jListCaveCarryItems.getSelectionModel();
    listSelectionModel.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
    this.listSelectionModel.addListSelectionListener( new SharedListSelectionHandler());
    //for debug purpose,see the world grid in console
    game.drawCaves();
    //new JComboBox(Mood.values());
    createGridQuarePanels();
    //world.startGame(GameLevel.Beginner);
    update();
}


private class SharedListSelectionHandler implements ListSelectionListener {
    public void valueChanged(ListSelectionEvent listSelectionEvent) {
        ListSelectionModel lsm = (ListSelectionModel)listSelectionEvent.getSource();
         if (!lsm.isSelectionEmpty()) {
            Occupant opt = mapOccupants.get(Integer.toString(jListCaveCarryItems.getSelectedIndex()));
            System.out.println("selected index :" +jListCaveCarryItems.getSelectedIndex() +"[["+opt.getName()+"]]");
        }
    }
}

In the above code, when I am making selection on jList : jListCaveCarryItems, it triggers the SharedListSelectionHandler class. However, when I am clicking on the JList, it print out the selected value twice.

Can anyone help me to figure it out?

Thanks & Regards,

Was it helpful?

Solution

2 ListSelectionEvents are dispatched when the JList is selected—one during and another after the selection event. From How to Write a List Selection Listener

The isAdjusting flag is true if the user is still manipulating the selection, and false if the user has finished changing the selection.

Therefore, ensure that the ListSelectionEvent value is not adjusting.

public void valueChanged( ListSelectionEvent listSelectionEvent)  {  
  if ( !listSelectionEvent.getValueIsAdjusting() && !lsm.isSelectionEmpty()) {  
     Occupant opt = ...
     ...
  }  
}  
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top