2015-04-03 31 views
1

我做了一個單獨的可編輯組合框.....當你輸入一些東西在裏面的時候,你輸入的任何東西都會進入列表的底部。我遇到的問題是,當我點擊已經在組合框中的東西時,它不僅僅被選中,而且還作爲新條目再次添加到組合框中,創建「重複」關於如何防止?這是我的。我如何保持組合框中的項目不會在javafx中複製?

import javafx.scene.*; 
import javafx.scene.control.*; 
import javafx.scene.layout.GridPane; 
import javafx.geometry.*; 
import javafx.stage.*; 
import javafx.application.Application; 
import javafx.collections.FXCollections; 
import javafx.collections.ObservableList; 

public class ComboBoxProblem extends Application { 

Scene scene1; 

ObservableList<String> randomStrings; 





public void start(Stage primaryStage)throws Exception{ 
    primaryStage.setTitle("ComboBox Problem!"); 
    primaryStage.setResizable(false); 
    primaryStage.sizeToScene(); 

    GridPane gridPane = new GridPane(); 

    scene1 = new Scene(gridPane); 

    ComboBox<String> box1 = new ComboBox<String>(); 

    randomStrings = FXCollections.observableArrayList(
      "Cool","Dude","BRO!","Weirdo","IDK" 

    ); 



    box1.setItems(randomStrings); 

    box1.setEditable(true); 

    box1.setValue(null); 
    box1.setOnAction(event -> { 
     String value = 

     box1.valueProperty().getValue(); 


     if(value != String.valueOf(randomStrings)){ 


      randomStrings.addAll(box1.valueProperty().getValue()); 
      box1.setValue(null); 
     } 


    }); 
    gridPane.setAlignment(Pos.CENTER); 
    gridPane.setConstraints(box1,0,0); 



    gridPane.getChildren().addAll(box1); 


    primaryStage.setScene(scene1); 
    primaryStage.show(); 

    } 




    public static void main(String[] args) { 
    launch(args); 

    } 

    } 
+0

@ItachiUchiha再次謝謝回答但我的小白問題,另外一個我真的很感激你的幫助 – 2015-04-03 06:30:34

+0

歡迎堆棧溢出。請通過[常見問題](http://stackoverflow.com/tour)。對於初學者來說,如果你想傳達一些信息,請對答案發表評論。如果它有助於解決您的問題,請接受答案。如果沒有人做過,並且您已經重新創建了可以解決問題的解決方案,則可以發佈並接受它。接受答案有助於未來的讀者面臨類似的問題。 – ItachiUchiha 2015-04-03 06:50:30

回答

1

只需在按鈕的動作中添加另一個條件來檢查該字符串是否已存在於項目列表中。如果沒有,請添加它。

!box1.getItems().contains(value) 

該條件被添加到以下語句。

if (!value.equals(String.valueOf(randomStrings)) && 
            !box1.getItems().contains(value)){ 
    randomStrings.addAll(value); 
    box1.setValue(null); 
} 

由於正確地指出的@uluk,你是比較字符串的方式不正確,你必須在場所使用equals!=

0

字符串值與!===運營商相比是錯誤的。

value != String.valueOf(randomStrings) // Incorrect 
value.equals(String.valueOf(randomStrings)) // Correct but not logical in your use case 

您可以檢查輸入值,然後將其添加到組合框的項目:

box1.setOnAction(event -> 
{ 
    if (box1.getValue() != null && !box1.getValue().trim().isEmpty()) 
    { 
     String value = box1.getValue().trim(); 
     if (!randomStrings.contains(value)) 
     { 
      randomStrings.add(value); 
      box1.setValue(null); 
     } 
    } 
}); 
相關問題