3 Replies Latest reply on Feb 27, 2013 4:15 PM by csh

    treeView has a java.lang.NullPointerException


      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.....

           public void initialize(URL arg0, ResourceBundle arg1) {     
           tree.setOnMouseClicked(new EventHandler(){
                public void handle(Event arg0) {
      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
          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 {
          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
            thanks very much.
            • 3. Re: treeView has a java.lang.NullPointerException
              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: