Vikas Singh
Vikas Singh

Reputation: 165

How to SetValue Of ComboBox With Given Id Value ?

I have tried the code to create a combobox with Id and Value Pair. Now I want to set the value of combobox with the specified Id passed. Example: I want to set the Value of combobox with employee name whose salary is 1400.0

package demo;

import javafx.application.Application;
import javafx.collections.FXCollections;
import javafx.collections.ObservableList;
import javafx.scene.Scene;
import javafx.scene.control.ComboBox;
import javafx.scene.layout.StackPane;
import javafx.stage.Stage;

/**
 *
 * @author vikassingh
 */
public class Demo extends Application {

    private final ObservableList<Employee> data
            = FXCollections.observableArrayList(
                    new Employee("Azamat", 2200.15),
                    new Employee("Veli", 1400.0),
                    new Employee("Nurbek", 900.5));

    @Override
    public void start(Stage primaryStage) {
        ComboBox<Employee> combobox = new ComboBox<>(data);

        // testing
        //combobox.getSelectionModel().selectFirst();
        //combobox.setValue(1400.0); // How to set value with specific Id Passed
        // End testing

        StackPane root = new StackPane();
        root.getChildren().add(combobox);
        primaryStage.setScene(new Scene(root, 300, 250));
        primaryStage.show();
    }

    public static class Employee {

        private String name;
        private Double salary;

        @Override
        public String toString() {
            return name;
        }

        public Employee(String name, Double salary) {
            this.name = name;
            this.salary = salary;
        }

        public String getName() {
            return name;
        }

        public void setName(String name) {
            this.name = name;
        }

        public Double getSalary() {
            return salary;
        }

        public void setSalary(Double salary) {
            this.salary = salary;
        }
    }

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

Upvotes: 0

Views: 855

Answers (1)

fabian
fabian

Reputation: 82461

Finding the correct Employee in the data list can be done using the same technique you'd use for any other Collection / List: iterate through the collection and find the first element that matches the criterion. The Streams API provides a simple way to do this:

Predicate<Employee> matcher = employee -> employee.getSalary() == 1400d;
Optional<Employee> opt = data.stream().filter(matcher).findAny();

combobox.setValue(opt.orElse(null)); // set found employee or null, if none was found.

Upvotes: 2

Related Questions