title: How do i put a focus listener on a Treecell in JavaFX?
body: <p>I am building am application where I need to have a tree view alongside a pane where data is presented.  When someone selects an item in the tree view, the application must identify what they have selected and seek the correct data from a database, then present it in the format I've chosen.  It must not matter how the user selects the item in the tree view (mouse click, tabbing, arrow keys, etc), just that when an item gets focus, a method is triggered to present the data to the user.</p>
  <p>I got this working perfectly for <strong>mouse clicks only</strong> in the following way:</p>
  <pre><code>    // Application thread method to build the tree map, used in the generateTree
      // method.
      public void treeBuilder(TreeMap&lt;ModelSites, ArrayList&lt;ModelPlants&gt;&gt; map) {
          
          TreeMap&lt;ModelSites, ArrayList&lt;ModelPlants&gt;&gt; treeMap = map;
  
          final TreeItemProperties&lt;String, String&gt; rootTreeItem = new TreeItemProperties&lt;String, String&gt;(&quot;EMT&quot;, null);
  
          TreeItemProperties&lt;String, Integer&gt; site = null;
          TreeItemProperties&lt;String, Integer&gt; plant = null;
          
          for (Map.Entry&lt;ModelSites, ArrayList&lt;ModelPlants&gt;&gt; entry : treeMap.entrySet()) {
              site = new TreeItemProperties&lt;String, Integer&gt;(entry.getKey().getLongName(), entry.getKey().getPrimaryKey());
              rootTreeItem.getChildren().add(site);
  
              if (site.getValue().equalsIgnoreCase(&quot;test item&quot;)) {
                  site.setExpanded(true);
              }
  
              for (int i = 0; i &lt; entry.getValue().size(); i++) {
                  plant = new TreeItemProperties&lt;String, Integer&gt;(entry.getValue().get(i).getSitePlantId() + &quot; &quot; + entry.getValue().get(i).getShortName(), entry.getValue().get(i).getPrimaryKey());
                  site.getChildren().add(plant);
              }
          }
          
          //Cell Factory is used to effectively turn the tree items into nodes, which they are not natively.
          //This is necessary to have actions linked to the tree items (eg. double click an item to open an edit window).
          emtTree.setCellFactory(new Callback&lt;TreeView&lt;String&gt;, TreeCell&lt;String&gt;&gt;() {
  
              @Override
              public TreeCell&lt;String&gt; call(TreeView&lt;String&gt; param) {
                  FactoryTreeCell&lt;String&gt; cell = new FactoryTreeCell&lt;String&gt;();
  
                  cell.setOnMouseClicked(event -&gt; {
                      if (!cell.isEmpty()) {
                          @SuppressWarnings(&quot;unchecked&quot;)
                          TreeItemProperties&lt;String, Integer&gt; treeItem = (TreeItemProperties&lt;String, Integer&gt;) cell.getTreeItem();
                          generateEquipmentPanes(treeItem.getPropertyValue());
                      }
                  });
                  return cell;
              }
          });
  
          rootTreeItem.setExpanded(true);
          emtTree.setRoot(rootTreeItem);
      }
  
  // Populate the main screen with all equipment items in the selected plant.
      public void generateEquipmentPanes(int plantId) {
  
          int plant = plantId;
          
          Task&lt;LinkedList&lt;ModelEquipment&gt;&gt; task = new Task&lt;LinkedList&lt;ModelEquipment&gt;&gt;() {
              @Override
              public LinkedList&lt;ModelEquipment&gt; call() {
                  LinkedList&lt;ModelEquipment&gt; equipmentList = DAOEquipment.listEquipmentByPlant(plant);
                  return equipmentList;
              }
          };
  
          // When list is built successfully, send the results back to the application
          // thread to load the equipment panes in the GUI.
          task.setOnSucceeded(e -&gt; equipmentPaneBuilder(task.getValue()));
          task.setOnFailed(e -&gt; task.getException().printStackTrace());
          task.setOnCancelled(null);
  
          String methodName = new Object() {}.getClass().getEnclosingMethod().getName();
  
          Thread thread = new Thread(task);
          thread.setName(methodName);
          //System.out.println(&quot;Thread ID: &quot; + thread.getId() + &quot;, Thread Name: &quot; + thread.getName());
          thread.setDaemon(true);
          thread.start();
      }
  
      // Application thread method to build the equipment panes, used in the
      // generateEquipmentPanes method.
      public void equipmentPaneBuilder(LinkedList&lt;ModelEquipment&gt; list) {
          LinkedList&lt;ModelEquipment&gt; equipmentList = list;
          
          EquipmentPanels.getChildren().clear();
  
          for (int i = 0; i &lt; equipmentList.size(); i++) {
              ModelEquipment item = equipmentList.get(i);
  
              try {
                  PaneEquipment equipmentPane = new PaneEquipment();
                  equipmentPane.updateFields(item.getTechId(), item.getShortName(), item.getLongDesc()); equipmentPane.setId(&quot;equipPane&quot; + i);
                              
                  EquipmentPanels.getChildren().add(equipmentPane);
              } catch (Exception e) {
                  e.printStackTrace();
              }
          }
      }
  </code></pre>
  <p>I've done a tonne of searching and I sort of figured out how to implement listeners instead of handlers as this seemed to be the way to do what I want - put a listener on a property of the cell.  But when replace the event handler with the listener, like the below two examples, I get many issues.</p>
  <pre><code>                emtTree.getSelectionModel().selectedItemProperty().addListener((observable, oldValue, newValue) -&gt; {
                      if (newValue != null) {
                          @SuppressWarnings(&quot;unchecked&quot;)
                          TreeItemProperties&lt;String, Integer&gt; treeItem = (TreeItemProperties&lt;String, Integer&gt;) cell.getTreeItem();
                          generateEquipmentPanes(treeItem.getPropertyValue());
                      }
                  });
  </code></pre>
  <pre><code>                cell.focusedProperty().addListener(new ChangeListener&lt;Boolean&gt;() {
  
                      @Override
                      public void changed(ObservableValue&lt;? extends Boolean&gt; observable, Boolean oldValue, Boolean newValue) {
                          if (!cell.isEmpty()) {
                              @SuppressWarnings(&quot;unchecked&quot;)
                              TreeItemProperties&lt;String, Integer&gt; treeItem = (TreeItemProperties&lt;String, Integer&gt;) cell.getTreeItem();
                              generateEquipmentPanes(treeItem.getPropertyValue());
                          }
                      }
                      
                  });
  </code></pre>
  <p>For a start I get <code>nullpointerexceptions</code> every time I click on a tree item, which comes from the line <code>generateEquipmentPanes(treeItem.getPropertyValue());</code>.  Secondly, it tends to pick data from the wrong item, not the one I selected.  Then after a few clicks it seems to break down altogether and do nothing except provide more <code>nullpointerexceptions</code>.</p>
  <p>From what I can understand, I think that the issue is the location of the listener relative to the variables that need to be passed to the method <code>generateEquipmentPanes</code>.  And something about removing listeners at a certain point and re-adding them later.</p>
  <p>Should I somehow be putting the listener into the cell factory?  At the moment it just looks like this:</p>
  <pre><code>import javafx.scene.control.TreeCell;
  
  public class FactoryTreeCell&lt;T&gt; extends TreeCell&lt;T&gt; {
      
      public FactoryTreeCell() {
      }
      
      /*  
       * The update item method simply displays the cells in place of the tree items (which disappear when setCellFactory is set.
       * This can be used for many more things (such as customising appearance) not implemented here.
      */
      @Override
      protected void updateItem(T item, boolean empty) {
          super.updateItem(item, empty);
          
          if (empty || item == null) {
              setText(null);
              setGraphic(null);   //Note that a graphic can be many things, not just an image.  Refer openJFX website for more details.
          } else {
              setText(item.toString());
          }
      }
      
  }
  </code></pre>
  <p>Another thing I've noticed is that there are other ways to implement the <code>Callback</code>, that might work better with listeners, but I don't know how to do that.</p>
  <p>I've been stuck on this for ages so a breakthrough would be great.</p>