13

我有一个员工列表,我需要在组合框中呈现其姓名以供用户选择。以下代码呈现下拉列表中的名称,但是当我选择一个名称时,组合显示的文本包含完整的 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() 方法?

4

1 回答 1

21

在您的 上调用setButtonCellComboBox,提供适当的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);
            }
        }
    }
}

样本输出:

组合框自定义按钮示例

于 2012-11-13T22:11:48.313 回答