2016-07-27 127 views
1

我有一個ComboBox,它具有以下代碼所示的實現。我面臨的問題是我只能觸發ChangeListener一次選擇的項目。我想觸發多次,因爲我點擊相同的項目。爲同一項目觸發組合框選擇事件

int lastGridRowPos = 4; 
ObservableList<String> options = FXCollections.observableArrayList(
       "IdentityFile", 
       "LocalForward", 
       "RemoteForward", 
       "ForwardAgent", 
       "ForwardX11" 
     ); 

ComboBox propertyBox = new ComboBox(options); 
propertyBox.valueProperty().addListener(new ChangeListener<String>() { 
    @Override 
    public void changed(ObservableValue ov, String t, String t1) { 
     System.out.println("SELECTED=" + t1); 
     int rowCounter = getRowCount(grid); 
     grid.add(new Label(t1), 0, rowCounter + 1); 
     TextField field = newTextFieldWithIdPrompt(t1.toUpperCase(), ""); 
     grid.add(field, 1, rowCounter + 1); 
     propertyBox.getSelectionModel().clearSelection(); 
    } 
}); 

我試圖用propertyBox.getSelectionModel().clearSelection();但它不工作以清除選擇,這樣我可以在同一項目再次點擊(希望組合框看到了項目的變化)。

回答

2

我幾乎可以肯定,一個簡單的解決方案存在,但你可以嘗試使用setCellFactory並添加EventFilter返回的ListCell實例:

propertyBox.setCellFactory(param -> { 
    final ListCell<String> cell = new ListCell<String>() { 
     @Override 
     public void updateItem(String item, boolean empty) { 
      super.updateItem(item, empty); 
      if (!empty) 
       setText(item); 
     } 
    }; 
    cell.addEventFilter(MouseEvent.MOUSE_PRESSED, e -> { 
     propertyBox.setValue(null); 
     propertyBox.getSelectionModel().select(cell.getItem()); 

     e.consume(); 
    }); 
    return cell; 
}); 

這些ListCell旨意捕捉鼠標按下事件列表ComboBox中的項目並消耗這些事件。然後他們手動將ComboBoxvalueProperty設置爲空(以刪除選擇),然後將該屬性設置爲ListCell顯示的項目。

然後在的ChangeListenervalueProperty你只需要檢查null S:

propertyBox.valueProperty().addListener((obs, oldVal, newVal) -> { 
    if (newVal != null) 
     System.out.println("Selected: " + newVal); 
}); 

附加說明:

我不知道你的確切使用情況,但也許一個MenuMenuItem s是更好的解決方案。

+0

感謝您的解決方案(我仍然必須嘗試在我的情況)。現在,當你說出這些話時,我想知道爲什麼菜單不適合我。我會看看菜單。我想要做的就是提供一個供用戶選擇的物品清單,他可以從哪裏允許他們一次又一次地選擇相同的物品。 – summerNight