title: Deselect an item on an javafx ListView on click
body: <p>I'm using a ListView control in a JavaFX application. It is set for MULTIPLE selection mode. I know as a user, I can Ctrl-Click an item to deselect it, but this is not intuitive enough for my users. I want a way to click a second time to deselect it. In other words click once - select; click selected item and it becomes unselected.</p>
  
  <p>I've tried using both a ChangeListener and an onMouseClicked event. Neither works very well. Below are code snippets of each.</p>
  
  <p><strong>ChangeListener:</strong></p>
  
  <p>effect - first item in the list is NEVER selected. I click on it and it stays unclicked. No effect on items 2..n</p>
  
  <pre><code>listView.getSelectionModel().selectedItemProperty().addListener(new ChangeListener&lt;SpecificAlgorithmData&gt;() {
      @Override
      public void changed(final ObservableValue observableValue, final SpecificAlgorithmData oldData, final SpecificAlgorithmData newData) {
  
          //if already selected then deselect it
          int selectedIndex = listView.getSelectionModel().getSelectedIndex();
          System.out.println("selected " + selectedIndex);
          System.out.println("all selected" + listView.getSelectionModel().getSelectedIndices());
          if (!selecting &amp;&amp; !listView.getSelectionModel().getSelectedIndices().contains(selectedIndex)){
  
  
              Iterator &lt;Integer&gt; iterator = listView.getSelectionModel().getSelectedIndices().iterator();
              selecting = true;
              listView.getSelectionModel().select(-1);//deselect all
  
              while (iterator.hasNext()){
                  int index = iterator.next();
                  if (index!= selectedIndex){
                      listView.getSelectionModel().select(index);
                  }
              }
              selecting = false;
          }
      }
  }
  </code></pre>
  
  <p><strong>onClick:</strong></p>
  
  <p>No effect, since I'm not sure how to get the index of the one I just clicked. Being hard coded, this simply disallows of ever selecting item 2.</p>
  
  <pre><code>listView.setOnMouseClicked(new EventHandler&lt;MouseEvent&gt;() {
      @Override
      public void handle(final MouseEvent mouseEvent) {
          int selectedItem = 2; //FIXME: How to I get the index of clicked item?
          if (listView.getSelectionModel().isSelected(selectedItem)){
              listView.getSelectionModel().clearSelection(selectedItem);
          }
      }
  });
  </code></pre>