如何使用给定的ID值设置ComboBox的Value? [英] How to SetValue Of ComboBox With Given Id Value ?

查看:108
本文介绍了如何使用给定的ID值设置ComboBox的Value?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我尝试使用代码创建具有ID和值对的组合框。现在,我要设置带有指定ID的combobox的值。示例:我想用员工名称为1400.0的雇员姓名设置组合框的值。

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


推荐答案

查找数据列表中正确的 Employee 可以使用与其他任何<$ c相同的技术来完成$ c> Collection / List :遍历集合并找到与条件匹配的第一个元素。 Streams API提供了一种执行此操作的简单方法:

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.

这篇关于如何使用给定的ID值设置ComboBox的Value?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆