使用JavaFX 2的组合框渲染POJO而不覆盖toString()方法 [英] Rendering a POJO with JavaFX 2's Combo Box without overriding the toString() method
问题描述
我有一个员工列表,我需要在组合框中呈现其名称供用户选择。下面的代码在下拉列表中呈现名称,但是当我选择名称时,组合的显示文本包含完整的POJO标识,字符串如src.org.entities.Employee@449ac7ce
I have a list of employees whose names I need to render on a combo box for the user to select. The following code renders the names on the dropdown list, but when I select a name, the combo's displayed text contains the full POJO's identity, a string like "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( )方法?
Is there a way to make the displayed text renders the selected name as well without overriding the POJO's toString() method?
推荐答案
调用 ComboBox上的javafx / scene / control / ComboBox.html#setButtonCell%28javafx.scene.control.ListCell%29rel =nofollow noreferrer> setButtonCell ,提供适当的 ListCell
渲染器实现以显示员工姓名。
Invoke setButtonCell on your ComboBox
, providing an appropriate ListCell
renderer implementation to display the employee name.
例如:
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);
}
}
}
}
示例输出:
这篇关于使用JavaFX 2的组合框渲染POJO而不覆盖toString()方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!