2016-12-03 19 views
-2

我認爲我寫了我的Java代碼很好,但仍然收到錯誤。如何總結排列choiceBox <integer>值與JavaFX

這是代碼:

所有程序相遇,讓我直接去有問題的代碼的一部分。

Int sumofc = 0; 
VBox vlay = new VBox(10); 

ChoiceBox<Integer> c1[] = new ChoiceBox[10] 
For (int x=0;x<10;x++){ 
    c1[x] = new ChoiceBox<>(); 
    C1[x].getItems().add(1); 
    C1[x].getItems().add(2); 
    C1[x].getItems().add(3); 
    Vlay.getChildren().add(c1[x]); 
    sumofc += c1[x].getValue(); 
} 

sumofc不加入的值。

+0

那些大寫/小寫錯誤只是錯別字我猜? – fabian

+0

瞭解你在'sumofc'中的期望會幫助我們幫助你。 – crazyhatfish

回答

0

即使將它們添加到場景之前,您也可以從選擇框中讀取值。這意味着用戶沒有以任何方式與ChoiceBox進行交互。相反,當用戶以有意義的方式與控件交互時應該閱讀,例如,通過選擇不同的值。

而且默認選中的值是null這會導致NullPointerException,當您嘗試自動拆箱它,因爲它相當於

sumofc += c1[x].getValue().intValue(); 

考慮到這些因素,你可以重寫類似這樣的代碼:

VBox vlay = new VBox(10); 

ChoiceBox<Integer> c1[] = new ChoiceBox[10]; 

InvalidationListener listener = o -> { 
    int sumofc = 0; 
    for (ChoiceBox<Integer> cb : c1) { 
     Integer value = cb.getValue(); 
     if (value != null) { 
      sumofc += value; 
     } 
    } 

    // do something with sumofc 
    System.out.println(sumofc); 
}; 

for (int x = 0; x < c1.length; x++) { 
    c1[x] = new ChoiceBox<>(); 
    c1[x].getItems().addAll(1, 2, 3); 
    vlay.getChildren().add(c1[x]); 
    c1[x].valueProperty().addListener(listener); 
} 
+0

如果我使用(我的 「概括的選擇值BTN」)是這樣的:btn.setOnAction(E - >的System.out.println(C [0] .getValues()+ C [1] .getValues()))之外的for循環它執行求和,但我希望它將數組choiceBox值整數化爲數組中的整數 –