我如何防止 comboBox 中的项目在 javafx 中重复?

how do i keep the items in a comboBox from duplicating in javafx?

我制作了一个可编辑的组合框.....当你在其中输入内容时,无论你输入什么都会出现在列表的底部。我遇到的问题是,当我单击组合框中已有的内容时,它不仅会被选中,还会作为新条目再次添加到组合框中,从而创建 "Duplicate" 关于我如何可以的任何想法防止那个?这是我的。

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);

  }

  }

只需在按钮的操作上添加另一个条件即可检查字符串是否已存在于项目列表中。如果没有,请添加。

!box1.getItems().contains(value)

条件是要添加到下面的语句中。

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

正如@uluk 正确指出的那样,您比较字符串的方式不正确,您必须使用 equals 代替 !=

将字符串值与 !=== 运算符进行比较是错误的。

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 );
        }
    }
} );