title: Implementing tab functionality for CheckBox cells in TableView
body: <p>I've created a TableView where each cell contains a TextField or a CheckBox. In the TableView you're supposed to be able to navigate left and right between cells using TAB and SHIFT+TAB, and up and down between cells using the UP and DOWN keys. </p>
  
  <p>This works perfectly when a text field cell is focused. But when a check box cell is focused, the tab funcationality behaves strange. You can tab in the opposite direction of the cell you tabbed from, but you can't switch tab direction. </p>
  
  <p>So for instance if you tabbed to the check box cell using only the TAB key, then SHIFT+TAB wont work. But if you tab to the next cell using the TAB key, and then TAB back using SHIFT+TAB (assuming the next cell is a text field cell), then TAB wont work.</p>
  
  <p>I've tried running any code handling focus on the UI thread using <code>Platform.runLater()</code>, without any noteable difference. All I know is that the TAB <code>KeyEvent</code> is properly catched, but the check box cell and the check box never loses focus in the first place anyway. I've tried for instance removing its focus manually by doing e.g. <code>getParent().requestFocus()</code> but that just results in the parent being focused instead of the next cell. What makes it strange is that the same code is executed and working properly when you tab in the opposite direction of the cell you came from.</p>
  
  <p>Here's a MCVE on the issue. Sadly it does not really live up to the "M" of the abbreviation:</p>
  
  <pre><code>import java.util.List;
  
  import javafx.application.Application;
  import javafx.beans.property.SimpleStringProperty;
  import javafx.beans.property.StringProperty;
  import javafx.collections.FXCollections;
  import javafx.collections.ObservableList;
  import javafx.scene.Scene;
  import javafx.scene.control.CheckBox;
  import javafx.scene.control.TableCell;
  import javafx.scene.control.TableColumn;
  import javafx.scene.control.TableView;
  import javafx.scene.control.TextField;
  import javafx.scene.input.KeyCode;
  import javafx.scene.input.KeyEvent;
  import javafx.stage.Stage;
  
  public class AlwaysEditableTable extends Application {
      public void start(Stage stage) {
  
          TableView&lt;ObservableList&lt;StringProperty&gt;&gt; table = new TableView&lt;&gt;();
          table.setEditable(true);
          table.getSelectionModel().setCellSelectionEnabled(true);
          table.setPrefWidth(510);
  
          // Dummy columns
          ObservableList&lt;String&gt; columns = FXCollections.observableArrayList("Column1", "Column2", "Column3", "Column4",
                  "Column5");
  
          // Dummy data
          ObservableList&lt;StringProperty&gt; row1 = FXCollections.observableArrayList(new SimpleStringProperty("Cell1"),
                  new SimpleStringProperty("Cell2"), new SimpleStringProperty("0"), new SimpleStringProperty("Cell4"),
                  new SimpleStringProperty("0"));
          ObservableList&lt;StringProperty&gt; row2 = FXCollections.observableArrayList(new SimpleStringProperty("Cell1"),
                  new SimpleStringProperty("Cell2"), new SimpleStringProperty("1"), new SimpleStringProperty("Cell4"),
                  new SimpleStringProperty("0"));
          ObservableList&lt;StringProperty&gt; row3 = FXCollections.observableArrayList(new SimpleStringProperty("Cell1"),
                  new SimpleStringProperty("Cell2"), new SimpleStringProperty("1"), new SimpleStringProperty("Cell4"),
                  new SimpleStringProperty("0"));
          ObservableList&lt;ObservableList&lt;StringProperty&gt;&gt; data = FXCollections.observableArrayList(row1, row2, row3);
  
          for (int i = 0; i &lt; columns.size(); i++) {
              final int j = i;
              TableColumn&lt;ObservableList&lt;StringProperty&gt;, String&gt; col = new TableColumn&lt;&gt;(columns.get(i));
              col.setCellValueFactory(param -&gt; param.getValue().get(j));
              col.setPrefWidth(100);
  
              if (i == 2 || i == 4) {
                  col.setCellFactory(e -&gt; new CheckBoxCell(j));
              } else {
                  col.setCellFactory(e -&gt; new AlwaysEditingCell(j));
              }
  
              table.getColumns().add(col);
          }
  
          table.setItems(data);
  
          Scene scene = new Scene(table);
          stage.setScene(scene);
          stage.show();
      }
  
      public static void main(String[] args) {
          launch();
      }
  
      /**
       * A cell that contains a text field that is always shown.
       */
      public static class AlwaysEditingCell extends TableCell&lt;ObservableList&lt;StringProperty&gt;, String&gt; {
  
          private final TextField textField;
  
          public AlwaysEditingCell(int columnIndex) {
  
              textField = new TextField();
  
              this.emptyProperty().addListener((obs, wasEmpty, isNowEmpty) -&gt; {
                  if (isNowEmpty) {
                      setGraphic(null);
                  } else {
                      setGraphic(textField);
                  }
              });
  
              // The index is not changed until tableData is instantiated, so this
              // ensure the we wont get a NullPointerException when we do the
              // binding.
              this.indexProperty().addListener((obs, oldValue, newValue) -&gt; {
  
                  ObservableList&lt;ObservableList&lt;StringProperty&gt;&gt; tableData = getTableView().getItems();
                  int oldIndex = oldValue.intValue();
                  if (oldIndex &gt;= 0 &amp;&amp; oldIndex &lt; tableData.size()) {
                      textField.textProperty().unbindBidirectional(tableData.get(oldIndex).get(columnIndex));
                  }
                  int newIndex = newValue.intValue();
                  if (newIndex &gt;= 0 &amp;&amp; newIndex &lt; tableData.size()) {
                      textField.textProperty().bindBidirectional(tableData.get(newIndex).get(columnIndex));
                      setGraphic(textField);
                  } else {
                      setGraphic(null);
                  }
  
              });
  
              // Every time the cell is focused, the focused is passed down to the
              // text field and all of the text in the textfield is selected.
              this.focusedProperty().addListener((obs, oldValue, newValue) -&gt; {
                  if (newValue) {
                      textField.requestFocus();
                      textField.selectAll();
                      System.out.println("Cell focused!");
                  }
              });
  
              // Switches focus to the cell below if ENTER or the DOWN arrow key
              // is pressed, and to the cell above if the UP arrow key is pressed.
              // Works like a charm. We don't have to add any functionality to the
              // TAB key in these cells because the default tab behavior in
              // JavaFX works here.
              this.addEventFilter(KeyEvent.KEY_RELEASED, e -&gt; {
                  if (e.getCode().equals(KeyCode.UP)) {
                      getTableView().getFocusModel().focus(getIndex() - 1, this.getTableColumn());
                      e.consume();
                  } else if (e.getCode().equals(KeyCode.DOWN)) {
                      getTableView().getFocusModel().focus(getIndex() + 1, this.getTableColumn());
                      e.consume();
                  } else if (e.getCode().equals(KeyCode.ENTER)) {
                      getTableView().getFocusModel().focus(getIndex() + 1, this.getTableColumn());
                      e.consume();
                  }
              });
          }
      }
  
      /**
       * A cell containing a checkbox. The checkbox represent the underlying value
       * in the cell. If the cell value is 0, the checkbox is unchecked. Checking
       * or unchecking the checkbox will change the underlying value.
       */
      public static class CheckBoxCell extends TableCell&lt;ObservableList&lt;StringProperty&gt;, String&gt; {
          private final CheckBox box;
  
          public CheckBoxCell(int columnIndex) {
  
              this.box = new CheckBox();
  
              this.emptyProperty().addListener((obs, wasEmpty, isNowEmpty) -&gt; {
                  if (isNowEmpty) {
                      setGraphic(null);
                  } else {
                      setGraphic(box);
                  }
              });
  
              this.indexProperty().addListener((obs, oldValue, newValue) -&gt; {
                  // System.out.println("Row: " + getIndex() + ", Column: " +
                  // columnIndex + ". Old index: " + oldValue
                  // + ". New Index: " + newValue);
  
                  ObservableList&lt;ObservableList&lt;StringProperty&gt;&gt; tableData = getTableView().getItems();
                  int newIndex = newValue.intValue();
                  if (newIndex &gt;= 0 &amp;&amp; newIndex &lt; tableData.size()) {
                      // If active value is "1", the check box will be set to
                      // selected.
                      box.setSelected(tableData.get(getIndex()).get(columnIndex).equals("1"));
  
                      // We add a listener to the selected property. This will
                      // allow us to execute code every time the check box is
                      // selected or deselected.
                      box.selectedProperty().addListener((observable, oldVal, newVal) -&gt; {
                          if (newVal) {
                              // If newValue is true the checkBox is selected, and
                              // we set the corresponding cell value to "1".
                              tableData.get(getIndex()).get(columnIndex).set("1");
                          } else {
                              // Otherwise we set it to "0".
                              tableData.get(getIndex()).get(columnIndex).set("0");
                          }
                      });
  
                      setGraphic(box);
                  } else {
                      setGraphic(null);
                  }
  
              });
  
              // If I listen to KEY_RELEASED instead, pressing tab next to a
              // checkbox will make the focus jump past the checkbox cell. This is
              // probably because the default TAB functionality is invoked on key
              // pressed, which switches the focus to the check box cell, and then
              // upon release this EventFilter catches it and switches focus
              // again.
              this.addEventFilter(KeyEvent.KEY_PRESSED, e -&gt; {
                  if (e.getCode().equals(KeyCode.UP)) {
                      System.out.println("UP key pressed in checkbox");
                      getTableView().getFocusModel().focus(getIndex() - 1, this.getTableColumn());
                      e.consume();
                  } else if (e.getCode().equals(KeyCode.DOWN)) {
                      System.out.println("DOWN key pressed in checkbox");
                      getTableView().getFocusModel().focus(getIndex() + 1, this.getTableColumn());
                      e.consume();
                  } else if (e.getCode().equals(KeyCode.TAB)) {
                      System.out.println("Checkbox TAB pressed!");
                      TableColumn&lt;ObservableList&lt;StringProperty&gt;, ?&gt; nextColumn = getNextColumn(!e.isShiftDown());
                      if (nextColumn != null) {
                          getTableView().getFocusModel().focus(getIndex(), nextColumn);
                      }
                      e.consume();
  
                      // ENTER key will set the check box to selected if it is
                      // unselected and vice versa.
                  } else if (e.getCode().equals(KeyCode.ENTER)) {
                      box.setSelected(!box.isSelected());
                      e.consume();
                  }
              });
  
              // Tracking the focused property of the check box for debug
              // purposes.
              box.focusedProperty().addListener((obs, oldValue, newValue) -&gt;
  
              {
                  if (newValue) {
                      System.out.println("Box focused on index " + getIndex());
                  } else {
                      System.out.println("Box unfocused on index " + getIndex());
                  }
              });
  
              // Tracking the focused property of the check box for debug
              // purposes.
              this.focusedProperty().addListener((obs, oldValue, newValue) -&gt;
  
              {
                  if (newValue) {
                      System.out.println("Box cell focused on index " + getIndex());
                      box.requestFocus();
                  } else {
                      System.out.println("Box cell unfocused on index " + getIndex());
                  }
              });
          }
  
          /**
           * Gets the column to the right or to the left of the current column
           * depending no the value of forward.
           * 
           * @param forward
           *            If true, the column to the right of the current column
           *            will be returned. If false, the column to the left of the
           *            current column will be returned.
           */
          private TableColumn&lt;ObservableList&lt;StringProperty&gt;, ?&gt; getNextColumn(boolean forward) {
              List&lt;TableColumn&lt;ObservableList&lt;StringProperty&gt;, ?&gt;&gt; columns = getTableView().getColumns();
              // If there's less than two columns in the table view we return null
              // since there can be no column to the right or left of this
              // column.
              if (columns.size() &lt; 2) {
                  return null;
              }
  
              // We get the index of the current column and then we get the next
              // or previous index depending on forward.
              int currentIndex = columns.indexOf(getTableColumn());
              int nextIndex = currentIndex;
              if (forward) {
                  nextIndex++;
                  if (nextIndex &gt; columns.size() - 1) {
                      nextIndex = 0;
                  }
              } else {
                  nextIndex--;
                  if (nextIndex &lt; 0) {
                      nextIndex = columns.size() - 1;
                  }
              }
  
              // We return the column on the next index.
              return columns.get(nextIndex);
          }
      }
  }
  </code></pre>