2015-12-28 105 views
1

我想在TableView中實現微調編輯器。我在這個主題上看到了各種各樣的StackOverflow,但他們似乎沒有解決這個問題。TableView中的JavaFX Spinner編輯器

我創建了從TableCell擴展的類。微調創建和所有內容,我無法讓微調進行編輯。

private final class SpinnerCell extends TableCell<Car, Integer> { 
    private final ScrollSpinner<Integer> spinner; 

    private SpinnerCell(int min, int max, int initial, int step) { 
     spinner = new ScrollSpinner<>(); 
     spinner.setValueFactory(new IntegerSpinnerValueFactory(min, max, initial, step)); 
     setEditable(true); 
    } 

    @Override 
    public void startEdit() { 
     if (!isEmpty()) { 
      super.startEdit(); 
      spinner.getValueFactory().setValue(getItem()); 

      setOnKeyTyped(event -> { //I tried spinner.setOnKeyTyped, spinner.getEditor().setOnKeyTyped with no luck 
       if (event.getCode() == KeyCode.ENTER) { 
        Log.debug("commiting"); 
        commitEdit(spinner.getValue()); //FIXME Never commited 
       } 
      }); 

      setText(null); 
      setGraphic(spinner); 
     } 
    } 

    @Override 
    public void cancelEdit() { 
     super.cancelEdit(); 

     setText(getItem().toString()); 
     setGraphic(null); 
    } 

    @Override 
    public void updateItem(Integer item, boolean empty) { 
     super.updateItem(item, empty); 

     if (empty) { 
      setText(null); 
      setGraphic(null); 
     } else { 
      if (isEditing()) { 
       setText(null); 
       setGraphic(spinner); 
      } else { 
       setText(getItem().toString()); 
       setGraphic(null); 
      } 
     } 
    } 
} 

}

回答

2

你必須改變onKeyTyped,以onKeyPressed。您還必須將commitEdit呼叫包裝在Platform.runLater中。

private final class SpinnerCell extends TableCell<Car, Integer> { 
    private final ScrollSpinner<Integer> spinner; 

    private SpinnerCell(int min, int max, int initial, int step) { 
     spinner = new ScrollSpinner<>(); 
     spinner.setValueFactory(new IntegerSpinnerValueFactory(min, max, initial, step)); 
     setEditable(true); 
    } 

    @Override 
    public void startEdit() { 
     if (!isEmpty()) { 
      super.startEdit(); 
      spinner.getValueFactory().setValue(getItem()); 

      setOnKeyPressed(event -> { 
       if (event.getCode() == KeyCode.ENTER) { 
        Platform.runLater(() -> { 
         commitEdit(spinner.getValue()); 
        }); 
       } 
      }); 

      setText(null); 
      setGraphic(spinner); 
     } 
    } 

    @Override 
    public void cancelEdit() { 
     super.cancelEdit(); 

     setText(getItem().toString()); 
     setGraphic(null); 
    } 

    @Override 
    public void updateItem(Integer item, boolean empty) { 
     super.updateItem(item, empty); 

     if (empty) { 
      setText(null); 
      setGraphic(null); 
     } else { 
      if (isEditing()) { 
       setText(null); 
       setGraphic(spinner); 
      } else { 
       setText(getItem().toString()); 
       setGraphic(null); 
      } 
     } 
    } 
}