【问题标题】:How to SetValue Of ComboBox With Given Id Value ?如何使用给定的 Id 值设置组合框的值?
【发布时间】:2023-03-19 12:26:01
【问题描述】:

我已尝试使用代码创建具有 Id 和值对的组合框。现在我想使用传递的指定 ID 设置组合框的值。示例:我想设置员工姓名为 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 的属性的设置器,您应该将属性实现为 javafx 属性,因为这是将观察者模式添加到您的类的简单方法,需要更新视图正确。另外:这是关于正确显示Employees 还是关于找到具有正确薪水的人?
  • @fabian : 找工资合适的员工,请给代码,我试试看。

标签: javafx combobox javafx-2 javafx-8


【解决方案1】:

data 列表中找到正确的Employee 可以使用与任何其他Collection / List 相同的技术来完成:遍历集合并找到与条件匹配的第一个元素. Streams API 提供了一种简单的方法来做到这一点:

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.

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2021-01-22
    • 2011-10-05
    • 2020-10-01
    • 1970-01-01
    • 1970-01-01
    • 2020-12-17
    • 2014-02-15
    相关资源
    最近更新 更多