1

I am trying to convert an object (selected item on jList1) to a string but it is returning null.

I have tried:

Object object1 = jList1.getSelectedValue();
String string1 = object.toString();

&

String string1 = jList1.getSelectedValue().toString();

But they are both returning null for me, is there something I am doing wrong?

This is what happens when button1 is pressed:

private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {
    Object object1 = jList1.getSelectedValue();
    String string1 = object1.toString();
    System.out.println(string1) 
}
6
  • Try String string1 = jList1.getSelectedValue(). Commented Sep 5, 2011 at 15:59
  • @Evan, that gives a Type Mismatch error (Cannot convert an object to string) Commented Sep 5, 2011 at 16:02
  • Okay, just making sure. The documentation examples for JList are unclear about how the return value is handled. Commented Sep 5, 2011 at 16:04
  • 2
    Post your SSCCE that demonstrates the problem. Commented Sep 5, 2011 at 16:10
  • 1
    Doesn't help, that is NOT a SSCCE. Read the link! Commented Sep 5, 2011 at 20:54

3 Answers 3

5

What type is this object? Have a look at the class's toString method if you can - chances are it is returning (incorrectly) null.

If getSelectedValue() returns a valid object, this is the only way for you to get null. If however it returned null, you should get a NullPointerException upon trying to call toString on the null reference. So I see no other possibility (provided the code snippet you posted is exact and your description is correct).

Sign up to request clarification or add additional context in comments.

2 Comments

I believe it is the getSelectedValue() that is returning null and the snippets I posted above are what I am trying to use aswell as the description.
@Jamie, why don't you add a debug printout to test your theory? E.g. if (object1 == null) System.out.println("selected value is null");
1

Chances are the toString() method on the selectedValue is returning null.

Has it been implemented properly?

3 Comments

I believe it is, although I do have something selected on the jList.
int index = jList1.getSelectedIndex(); use this to see if actually any of the value from the list is selected or not. If it is returning -1, then no value is selected.
@Rakesh, That returns 0, 1, 2, etc depending on which item was selected.
-4

Sorted this myself, not sure what was wrong but I copied the GUI and most of the code (apart from that section causing problems) to a new project re-wrote that part and it worked.

1 Comment

This answer doesn't help others who might come across the same problem.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.