【问题标题】:ItemListener itemStateChanged does not change when choosing an index with the same contentItemListener itemStateChanged 在选择具有相同内容的索引时不会改变
【发布时间】:2014-02-18 18:45:42
【问题描述】:

例如,我有一个带有值的 JComboBox:
{"weapon","armor","weapon"}
如果当前选择的索引是 0 (weapon) 并且我选择了索引 2 (weapon),它不会在我的 ItemListener 中触发 ItemStateChanged。虽然如果当前选择的索引为 0,而我选择了索引 1,它会触发 ItemStateChanged。

这是我现在的代码:

class CBListener implements ItemListener{
    @Override
    public void itemStateChanged(ItemEvent e){
       JComboBox temp = (JComboBox) e.getSource();
       int wordIndex = temp.getSelectedIndex(); // index of selected string in the list
       int row = sTable.getSelectedRow(); // row of the cell
       int col = sTable.getSelectedColumn(); // column of the cell

       sTable.setValueAt(listE.get(row)[wordIndex], row, 0);
        //System.out.println(listE.get(row)[wordIndex]);
       sTable.setValueAt(listI.get(row)[wordIndex], row, 1);
       sTable.setValueAt(listD.get(row)[wordIndex], row, 3);

    }        
}

如何修改我的代码,以便在我的示例中获得类似于索引 2 的索引?

【问题讨论】:

  • 在您对此束手无策之前,请重新考虑一下您是如何使用 JComboBox 的——您真的应该有两个名称完全相同但选择时具有不同效果的条目吗?
  • 是的,这两个 weapon 项目意味着不同的东西。这表明列表中有一个项目与另一个项目完全相同,但两者都是独立的对象。

标签: java jcombobox itemlistener


【解决方案1】:

我仍然建议在这两个项目之间进行一些区分,但如果你真的希望它们相同,我认为你必须创建一个 toString 值为“weapon”的对象,但其等于返回假。比如:

public BuyableItem( String description, int index ) {
:
:
}

public String toString() {
   return this.description;
}

public boolean equals( BuyableItem item ) {
   boolean retVal = this.description.equals( item.description );
   if( retVal ) {
      retVal = this.index == item.index;
   }
   return retVal;
}

那么你的 JComboBox 值可能是

{ new BuyableItem( "weapon", 0 ), new BuyableItem( "armor", 1 ), new BuyableItem( "weapon", 2 ) };

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-10-12
    • 1970-01-01
    • 1970-01-01
    • 2011-02-09
    • 1970-01-01
    相关资源
    最近更新 更多