21

我刚刚开始学习 JavaFX 2。
现在我正在尝试构建一个示例应用程序。然后我陷入了组合框。
我没有在 JavaFX 中找到任何对组合框键值对的引用。http://docs.oracle.com/javafx/2/api/index.html
上 的组合框 javadoc对键值对没有多说。

如何创建一个组合框,其中的项目具有不同的显示值和实际值?

4

3 回答 3

24

您有 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显示值是。 2. 第二种方法是设置组合框的 cellFactory 属性。 employee.toString()

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 实例。

于 2012-05-22T10:56:54.463 回答
16

还有另一种解决方案,实现StringConverter。它对对象非常有用:

public class Product {

    private String code;
    private String name;

    public Product(String code, String name) {
        this.code = code;
        this.name = name;
    }

    public String getCode() {
        return code;
    }

    public void setCode(String code) {
        this.code = code;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

}

转换器实现:

public class ProductConverter extends StringConverter<Product> {

    /** Cache of Products */
    private Map<String, Product> productMap = new HashMap<String, Product>();

    @Override
    public String toString(Product product) {
        productMap.put(product.getName(), product);
        return product.getName();
    }

    @Override
    public Product fromString(String name) {
        return productMap.get(name);
    }

}

视图中的代码:

    ComboBox<Product> cboProducts  = new ComboBox<Product>;
    cboProducts.setConverter(new ProductConverter());
    cboProducts.getItems().addAll(serviceManager.getProductList());

要获取产品的价值,可以调用 getValue() 方法:

cboProducts.getValue()
于 2012-06-08T22:45:23.797 回答
0

我知道这个问题很老,但是因为我只是花了几个小时在这个问题上毫无意义地挖掘,所以我必须分享结果。似乎具有覆盖 toString() 方法的 ComboBox 将字符串解析回恰到好处的对象,即使列表中有字符串重复也是如此。分辨率必须基于索引,并且 toString() 仅用于演示。

于 2014-08-10T08:10:23.137 回答