This week's book giveaway is in the Servlets forum.
We're giving away four copies of Murach's Java Servlets and JSP and have Joel Murach on-line!
See this thread for details.
The moose likes Swing / AWT / SWT and the fly likes Trouble using JComboBox Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login


Win a copy of Murach's Java Servlets and JSP this week in the Servlets forum!
JavaRanch » Java Forums » Java » Swing / AWT / SWT
Bookmark "Trouble using JComboBox" Watch "Trouble using JComboBox" New topic
Author

Trouble using JComboBox

Colart Brunton
Greenhorn

Joined: Dec 16, 2003
Posts: 4
Hi
I am having trouble getting the correct index from a JComboBox. My program's JComboBox allows for duplicated entries.
When the getSelectedIndex() method is used, it returns the index of the FIRST instance of the object that was selected!!! instead of returning the index to the actual item selected by the mouse!!
/**
* I need this labelIndex to be the index of the label selected!! not the *first instance of the label in the list.
*/
labelIndex = frame.labelsComboBox.getSelectedIndex();
Does anyone know how to remedy this?
Gregg Bolinger
GenRocket Founder
Ranch Hand

Joined: Jul 11, 2001
Posts: 15299
    
    6

Why don't you show us the code where you are filling your JComboBox so we can see if you are doing that correctly. Are you using a Model for the JComboBox? It's hard to debug someones problem when they don't show us some code.


GenRocket - Experts at Building Test Data
clio katz
Ranch Hand

Joined: Apr 30, 2004
Posts: 101
yes, this is the default behavior (as per api docs). if you want to get unique index for duplicate list items, you need to setup a custom renderer. this would be not too hard for what you need to do (unless you have, say, an editable combo box).
you can modify and use the sun ComboBoxRenderer class example at http://java.sun.com/docs/books/tutorial/uiswing/components/combobox.html, (just ignore the stuff about displaying an icon). both your 'itemStateChanged' listener and your 'getListCellRendererComponent' will provide you the correct selected index.
hth
 
It is sorta covered in the JavaRanch Style Guide.
 
subject: Trouble using JComboBox
 
Similar Threads
ComboBox Item Display
JComboBox
jComboBox
Duplicate items in JCombobox
JComboBox Action Issues.