我有这个错误,在填充JList之后,我尝试检索所选项的值。但是当我这样做时,它会被调用两次。
这是我的代码:
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()+"]]");
}
}
}
在上面的代码中,当我在jList:jListCaveCarryItems上进行选择时,它会触发SharedListSelectionHandler类。但是,当我单击JList时,它会打印出两次所选的值。
任何人都可以帮我弄清楚吗?
谢谢&的问候,
答案 0 :(得分:10)
ListSelectionEvents
时会分派 2 JList
- 在选择事件期间和之后另一个ListSelectionEvent
。来自How to Write a List Selection Listener
如果用户仍在操作选择,则isAdjusting标志为true,如果用户已完成更改选择,则为false。
因此,请确保public void valueChanged( ListSelectionEvent listSelectionEvent) {
if ( !listSelectionEvent.getValueIsAdjusting() && !lsm.isSelectionEmpty()) {
Occupant opt = ...
...
}
}
值未调整。
{{1}}