How to SetValue Of ComboBox With Given Id Value ?

|▌冷眼眸甩不掉的悲伤 提交于 2020-01-17 10:41:45

问题


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

回答1:


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.


来源:https://stackoverflow.com/questions/35953811/how-to-setvalue-of-combobox-with-given-id-value

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!