栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 面试经验 > 面试问答

JavaFX 2中的组合框键值对

面试问答 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

JavaFX 2中的组合框键值对

您有2种方法:
1.简单地覆盖

toString()
数据模型类中的方法。例:

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);        combobox.getSelectionModel().selectFirst(); // Select first as default        combobox.getSelectionModel().selectedItemProperty().addListener(new ChangeListener<Employee>() { @Override public void changed(Observablevalue<? extends Employee> arg0, Employee arg1, Employee arg2) {     if (arg2 != null) {         System.out.println("Selected employee: " + arg2.getName());     } }        });        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 + " (sal:" + salary + ")";        }        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类的重写的toString()。组合框的键(实际值)将是

Employee
实例,
employee.toString()
在这种情况下显示值是。
2.第二种方法是设置组合框的cellFactory属性。

combobox.setCellFactory(new Callback<ListView<Employee>, ListCell<Employee>>() {    @Override    public ListCell<Employee> call(ListView<Employee> arg0) {        return new ListCell<Employee>() { private final Button btn; {     setContentDisplay(ContentDisplay.GRAPHIC_ONLY);     btn = new Button(); } @Override protected void updateItem(Employee item, boolean empty) {     super.updateItem(item, empty);     if (item == null || empty) {         setGraphic(null);     } else {         btn.setStyle(item.getSalary() > 1000 ? "-fx-base:red" : "-fx-base: green");         btn.setText(item.getName() + "=" + item.getSalary());         setGraphic(btn);     } }        };    }});

这种方法可以更强大地控制单元格渲染。您不仅可以设置显示值的格式,还可以在单​​元格(在这种情况下为按钮)中包括任何节点(控件),并添加一些查看逻辑(item.getSalary()?“”:“”)。实际值保持不变,即Employee实例。



转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/469533.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号