使用JavaFX 2的组合框渲染POJO而不覆盖toString()方法

时间:2012-11-13 20:51:13

标签: javafx

我有一个员工列表,我需要在组合框中呈现其名称供用户选择。下面的代码在下拉列表中呈现名称,但是当我选择名称时,组合的显示文本包含完整的POJO标识,字符串如“src.org.entities.Employee@449ac7ce”

cboEmployees.setCellFactory(new Callback<ListView<Employee>, ListCell<Employee>>()
    {
        @Override
        public ListCell<Employee> call(ListView<Employee> p)
        {
            return new ListCell<Employee>()
            {
                @Override
                protected void updateItem(Employee item, boolean empty) {
                    super.updateItem(item, empty);

                    if (item != null)
                    {
                        setText(item.getName());
                    }
                }
            };
        }
    });

有没有办法让显示的文字呈现所选名称,而不会覆盖POJO的toString()方法?

1 个答案:

答案 0 :(得分:19)

ComboBox上调用setButtonCell,提供适当的ListCell渲染器实施,以显示员工姓名。

例如:

import javafx.application.Application;
import javafx.scene.Scene;
import javafx.scene.control.*;
import javafx.scene.layout.*;
import javafx.stage.Stage;
import javafx.util.Callback;

public class BasicComboBoxSample extends Application {
    public static void main(String[] args) { launch(args); }

    @Override public void start(Stage stage) {
        final Employee john = new Employee("John");
        final Employee jill = new Employee("Jill");
        final Employee jack = new Employee("Jack");

        final ComboBox<Employee> cboEmployees = new ComboBox();
        cboEmployees.setButtonCell(new EmployeeListCell());
        cboEmployees.setCellFactory(new Callback<ListView<Employee>, ListCell<Employee>>() {
            @Override public ListCell<Employee> call(ListView<Employee> p) {
                return new EmployeeListCell();
            }
        });
        cboEmployees.getItems().addAll(john, jill, jack);
        cboEmployees.setValue(jill);

        final StackPane layout = new StackPane();
        layout.getChildren().add(cboEmployees);
        layout.setStyle("-fx-background-color: cornsilk; -fx-padding: 15;");
        stage.setScene(new Scene(layout));
        stage.show();
    }    

    class Employee {
        public Employee(String name) { this.name = name; }
        private String name;
        public String getName() { return name; }
    }

    class EmployeeListCell extends ListCell<Employee> {
        @Override protected void updateItem(Employee item, boolean empty) {
            super.updateItem(item, empty);
            if (!empty && item != null) {
                setText(item.getName());
            } else {
                setText(null);
            }
        }
    }
}

示例输出:

combobox custom button sample