This discussion is archived
3 Replies Latest reply: Feb 27, 2013 8:15 AM by csh RSS

treeView has a java.lang.NullPointerException

987786 Newbie
Currently Being Moderated
Hi,guys

I got a TreeView issue which is said that java.lang.NullPointerException.below are my words:

public class TreeViewController<T> implements Initializable {
     
     public TreeView<T> tree;

.........there are some codes about the oher thing.....

     @Override
     public void initialize(URL arg0, ResourceBundle arg1) {     
     tree.setOnMouseClicked(new EventHandler(){
          @Override
          public void handle(Event arg0) {
               
               System.out.println(tree.getSelectionModel().getSelectedItem().getValue());
          }});
     }
}
I need to get the current clicked treeItem value.but once I use the codes : tree.getSelectionModel().getSelectedItem().getValue() or tree.getSelectionModel().getSelectedItem().toString(),I will get a java.lang.NullPointerException.and this issue occurs sometimes. and I have to use tree.getSelectionModel().getSelectedItems().get(0);instead.So,is this a issue? wish to get your help.thanks a million.
  • 1. Re: treeView has a java.lang.NullPointerException
    James_D Guru
    Currently Being Moderated
    If nothing is selected, tree.getSelectionModel().getSelectedItem() will return null. In this case, the call to getValue() will generate a NullPointerException.

    You need something like
    TreeItem<T> selectedItem = tree.getSelectionModel().getSelectedItem();
    if (selectedItem == null) {
      System.out.println("Nothing selected");
    } else {
      System.out.println(selectedItem.getValue());
    }
    Typically, to track changes in selection, you would add a change listener to the selected item property, rather than using a mouse event handler (though I think you still need to check for the case where nothing is selected).
  • 2. Re: treeView has a java.lang.NullPointerException
    987786 Newbie
    Currently Being Moderated
    thanks very much.
  • 3. Re: treeView has a java.lang.NullPointerException
    csh Journeyer
    Currently Being Moderated
    While JamesD is of course right, I still wonder, why tree.getSelectionModel().getSelectedItems().get(0) works then, because tree.getSelectionModel().getSelectedItems().get(0).getValue() should also produce a NullPointerException in that case.

    I've recently discovered 2 bugs, which are related to the selection model of ListView and are related to different values in getSelectedItem() and getSelectedItems().get(0)

    Maybe you encountered a third one.

    You might want to have a look:

    http://javafx-jira.kenai.com/browse/RT-27820
    http://javafx-jira.kenai.com/browse/RT-28637

Legend

  • Correct Answers - 10 points
  • Helpful Answers - 5 points