This week's book giveaway is in the Kotlin forum.
We're giving away four copies of Kotlin in Action and have Dmitry Jemerov & Svetlana Isakova on-line!
See this thread for details.
Win a copy of Kotlin in Action this week in the Kotlin forum!
  • Post Reply Bookmark Topic Watch Topic
  • New Topic

JList  RSS feed

 
M Nemonical
Greenhorn
Posts: 5
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
I dont understand. I do select the item in the list and myList.getSelectedValue() returns null. If I use getSelectedIndex() it returns -1, why?
F.
 
Nathan Pruett
Bartender
Posts: 4121
IntelliJ IDE Java Spring
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
"M Nemonical" -

Welcome to the JavaRanch! Please adjust your displayed name to meet the
JavaRanch Naming Policy.
You can change it here.

Why don't you post the code you're using so we can see what might be causing the problem?

Thanks! and welcome to the JavaRanch!
 
Chris Mathews
Ranch Hand
Posts: 2712
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
The answer to your question lies in the difference between primitives and objects and the fact that Java is strongly typed.
JList.getSelectedValue() returns an Object. The question is what happens if there is no selected value? In this case the developer has two options, throw an exception or return a value to represent no object being selected. Throwing an exception is not appropriate since an item not being selected is not an exceptional condition. Therefore we need to return a value to let the client know that nothing was selected. Since the return type is Object the most appropriate value for nothing is of course null.
JList.getSelectedIndex() returns an int. This time however we cannot return null because int is a primitive not an object. We still don't want to throw an exception, so now we need a int to return that represents nothing. Since the JList is indexed starting at 0, -1 becomes a good choice for nothing.
 
Don't get me started about those stupid light bulbs.
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!