wood burning stoves 2.0*
The moose likes Beginning Java and the fly likes Reading from ListBox. Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login


Win a copy of EJB 3 in Action this week in the EJB and other Java EE Technologies forum!
JavaRanch » Java Forums » Java » Beginning Java
Bookmark "Reading from ListBox." Watch "Reading from ListBox." New topic
Author

Reading from ListBox.

Drake Silver
Ranch Hand

Joined: Apr 21, 2002
Posts: 80
Hi, I'm wondering about how exactly you read an item from a list box.
I tried using the getSelectedIndex() and comparing to a string, but that didn't seem to work.
Could it be that I have to load the listbox items into an array, and from there compare with getSelectedIndex()?
any ideas would be helpful.
thanks


"Shh, Zog....here come one Now!"
Larry Jones
Greenhorn

Joined: Oct 22, 2002
Posts: 24
If you're talking about a JList, I think this is what you're looking for:
<code>
String[] data = {"one", "two", "three", "four"};
JList dataList = new JList(data);
dataList.setSelectedIndex(1); // selects "two"

//Gets the item from the list
//You must cast it to a String
String item = (String)dataList.getSelectedValue();
if (item.equals("two"))
{
System.out.println(item);//prints two
}
<code>
Drake Silver
Ranch Hand

Joined: Apr 21, 2002
Posts: 80
thankyou, I'll give that a try.
But..
I just ran across getSelectedValue().
When would I use getselectedIndex() over getSelectedValue()?
Plus, what are the diff's good and bad about each.
[ November 10, 2002: Message edited by: Drake Silver ]
Gregg Bolinger
GenRocket Founder
Ranch Hand

Joined: Jul 11, 2001
Posts: 15286
    
    6

Have you even bothered to look at the API for a JList or List yet?
You'll notice that getSelectedIndex() returns an INT and getSelectedValue() returns an OBJECT. That is the difference between the 2. There is not really a + or - to using either one. It depends on how you want to retrieve the data. However, if you are actually trying to retrieve the "String" of an item in your JList or List, use getSelectedValue() and cast the object to a String.


GenRocket - A Test Data Generation Platform
 
I agree. Here's the link: http://aspose.com/file-tools
 
subject: Reading from ListBox.
 
Similar Threads
Listbox Transfer
servlet
Detecting editable field entry in a JComboBox
Populate listbox from sql
how to retain selected value.....