Java - jList getSelectedValue problem
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.toStri开发者_JS百科ng();
System.out.println(string1)
}
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).
Chances are the toString() method on the selectedValue is returning null.
Has it been implemented properly?
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.
精彩评论