我有一个需要在组合框上呈现的名称的雇员列表供用户选择.以下代码在下拉列表中显示名称,但是当我选择一个名称时,组合显示的文本包含完整的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()); } } }; } });
解决方法
在您的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 (item != null) { setText(item.getName()); } } } }
样品输出: