2015-04-03 63 views
1

是否有連接兩個選擇框或組合框的方法?這並不重要。 我想要更改方框2(整數)中的項目,具體取決於方框1(字符串)上選擇的內容。連接兩個選擇框或組合框

例如:
箱一個:
蛋糕
餅乾

盒二:
如果蛋糕,那麼數字1,2,3,...,28,29,30。
如果是cookies,那麼數字1,2,3,....,27,28。
其他空箱子。

數字可以通過數組放入。我遇到的問題是如何使用事件處理程序來更改第二個框中的內容。
謝謝。

+0

您是否具有確定性功能,將Box 1的內容映射到Box 2的內容? – ItachiUchiha 2015-04-03 14:05:25

+0

你有你試過的代碼嗎? – Alupotha 2015-04-03 14:16:57

+0

不知道我明白你的意思,但我所嘗試的是通過使用if/else來更改Box 2的項目,但是它不成功。 – spacedout 2015-04-03 14:25:11

回答

1

根據您的要求,可以有不同的方法。可以是:

@Override 
public void start(Stage stage) 
{ 

    final Map<String, ObservableList<Integer>> map = new HashMap<>(); 
    map.put("cupcakes", FXCollections.observableArrayList(1,2,3,4,5,6)); 
    map.put("cookies", FXCollections.observableArrayList(11,12,13,14,15,16)); 

    final ComboBox<String> comboOne = new ComboBox<>(); 
    comboOne.getItems().addAll(
      "cupcakes", 
      "cookies", 
      "empty box" 
    ); 
    final ComboBox<Integer> comboTwo = new ComboBox<>(); 

    comboOne.getSelectionModel().selectedItemProperty().addListener(new ChangeListener<String>() 
    { 
     @Override 
     public void changed(ObservableValue<? extends String> observable, String oldValue, String newValue) 
     { 
      comboTwo.setItems( 
        map.containsKey(newValue) ? map.get(newValue) : FXCollections.emptyObservableList() 
      ); 
     } 
    }); 

    VBox grid = new VBox(20); 
    grid.getChildren().addAll(comboOne, comboTwo); 

    Scene scene = new Scene(grid, 450, 250); 
    stage.setScene(scene); 
    stage.show(); 
}