【发布时间】: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