Your wordpair_list
does not contain whatever list.getSelectedValue()
returns. Note that the indexOf() method will return -1
when the specified object is not contained within the list.
You can confirm this by printing/logging the value of i
.
In terms of fixing the code, if wordpair_list
actually did contain list.getSelectedValue()
, your code could be more concisely written as:
public void showTranslation(){
textField.setText(list.getSelectedValue().getWordB());
}
But since that value is not in the list, you'll have to try some other approach. One possibility is that you have confused your types, and are looking in the wordpair_list
for an object of an incompatible type. Another possibility is that you need to override equals()
(and as a consequence, also hashCode()
) so that your indexOf()
lookup succeeds.
More info on that last bit here: What issues should be considered when overriding equals and hashCode in Java?