Clickz
Clickz

Reputation: 75

How to make it so there are no duplicates in JavaFX ComboBox

In this program, you can add words to the ComboBox using a textfield. How would you make it so the program will not accept any words that are already in the ComboBox? I tried to make it so if the textfield input is equal to something in the ComboBox then it shouldn't add it but it will not work.

package gps_destinations_controller;

import gps_destinations_model.Model;
import java.io.BufferedReader;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.net.URL;
import java.util.ResourceBundle;
import javafx.event.ActionEvent;
import javafx.fxml.FXML;
import javafx.fxml.Initializable;
import javafx.scene.control.ComboBox;
import javafx.scene.control.Label;
import javafx.scene.control.SingleSelectionModel;
import javafx.scene.control.TextField;

public class Controller implements Initializable 
{
    @FXML TextField destinationInput;
    @FXML ComboBox<String> destinationList;
    private SingleSelectionModel<String> selectionModel;

    private Model model;

    @Override
    public void initialize(URL url, ResourceBundle rb) 
    {
    model = new Model();

    destinationList.getItems().addAll(model.getDestinations());

    selectionModel = destinationList.getSelectionModel();  

    selectionModel.select(model.getSelectedIndex());
        System.out.println(destinationList.getItems());



    }    

    @FXML protected void addDestination() 
    {
        String input = destinationInput.getText();

         if(!destinationList.getItems().equals(input))
         {
        destinationList.getItems().add(input);
         }


        model.addDestination(input);


        destinationInput.clear();

    }






    @FXML protected void itemSelected( ActionEvent event ) 
    {
    int index = selectionModel.getSelectedIndex();
    model.updateSelection(index);

    }
}

Upvotes: 3

Views: 642

Answers (1)

fabian
fabian

Reputation: 82461

You're comparing the items list itself to the element you want to add. This always results in false and the item is always added. You need to use contains to check, if an element is already in the list:

if(!destinationList.getItems().contains(input)) {
    destinationList.getItems().add(input);
}

Upvotes: 5

Related Questions