Win a copy of The Journey To Enterprise Agility this week in the Agile and Other Processes forum! And see the welcome thread for 20% off.
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
programming forums Java Mobile Certification Databases Caching Books Engineering Micro Controllers OS Languages Paradigms IDEs Build Tools Frameworks Application Servers Open Source This Site Careers Other all forums
this forum made possible by our volunteer staff, including ...
Marshals:
  • Jeanne Boyarsky
  • Liutauras Vilda
  • Campbell Ritchie
  • Tim Cooke
  • Bear Bibeault
Sheriffs:
  • Paul Clapham
  • Junilu Lacar
  • Knute Snortum
Saloon Keepers:
  • Ron McLeod
  • Ganesh Patekar
  • Tim Moores
  • Pete Letkeman
  • Stephan van Hulst
Bartenders:
  • Carey Brown
  • Tim Holloway
  • Joe Ess

Trouble using JComboBox  RSS feed

 
Greenhorn
Posts: 4
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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?
 
Ranch Hand
Posts: 15304
6
Chrome IntelliJ IDE Mac OS X
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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.
 
Ranch Hand
Posts: 101
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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.
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!