简体   繁体   中英

selected indexes of same value get first item not specified index

I have three jcomboboxes that all have the respected data in them, invoice id, invoice date and invoice amount. all three have action listeners on them that sends them to a class. in the class I run a switch case to see which combobox changed. from there I get that selected item and set the other two to that selected item. eg

index = jComboBox1.getSelectedIndex(); 
jComboBox3.setSelectedIndex(index);
jComboBox4.setSelectedIndex(index);

The problem I'm having is if the amounts are the same it selects the first index with that amount. how do I fix this?

The problem is that JComboBox internally uses setSelectedItem even when you call setSelectedIndex . The first item that equals is selected.

You can use a object wrapper for your amount field (I guess it is a double) that should take care of this.

This would be my interpretation of KDM's suggestion.

JComboBox<Object> idBox = new JComboBox<>();

Then when adding the objects:

idBox.add(new Object(){ public String toString(){ return invoice.id + "";}});

I think a better solution would be to use a custom renderer and have JComboBox, so that your invoices are stored in each box and just rendered differently, ie return the appropriate string.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM