gpt4 book ai didi

java swing jlist addListSelectionListener ListSelectionListener 调用了两次

转载 作者:塔克拉玛干 更新时间:2023-11-01 21:47:54 25 4
gpt4 key购买 nike

我有这个错误,在填充 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 时,它会打印出所选值两次。

谁能帮我弄清楚?

感谢和问候,

最佳答案

2 ListSelectionEvents 在选择 JList 时分派(dispatch)——一个在选择事件期间,另一个在选择事件之后。来自 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.

因此,请确保 ListSelectionEvent 值未调整。

public void valueChanged( ListSelectionEvent listSelectionEvent)  {  
if ( !listSelectionEvent.getValueIsAdjusting() && !lsm.isSelectionEmpty()) {
Occupant opt = ...
...
}
}

关于java swing jlist addListSelectionListener ListSelectionListener 调用了两次,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16886967/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com