属性表 https://controlsfx.bitbucket.io/org/controlsfx/control/PropertySheet.html确实支持一些开箱即用的属性编辑器,具体取决于属性类型。
以下示例是 ControlsFX 示例应用程序的扩展。它显示了 String、LocalDate、Enum、Boolean 和 Integer 类型如何分别映射到 TextField、DatePicker、ChoiceBox、CheckBox 和 NumericField。
public class PropertySheetExample extends VBox {
private static Map<String, Object> customDataMap = new LinkedHashMap<>();
static {
customDataMap.put("Group 1#My Text", "Same text"); // Creates a TextField in property sheet
customDataMap.put("Group 1#My Date", LocalDate.of(2000, Month.JANUARY, 1)); // Creates a DatePicker
customDataMap.put("Group 2#My Enum Choice", SomeEnumType.EnumValue); // Creates a ChoiceBox
customDataMap.put("Group 2#My Boolean", false); // Creates a CheckBox
customDataMap.put("Group 2#My Number", 500); // Creates a NumericField
}
class CustomPropertyItem implements PropertySheet.Item {
private String key;
private String category, name;
public CustomPropertyItem(String key) {
this.key = key;
String[] skey = key.split("#");
category = skey[0];
name = skey[1];
}
@Override
public Class<?> getType() {
return customDataMap.get(key).getClass();
}
@Override
public String getCategory() {
return category;
}
@Override
public String getName() {
return name;
}
@Override
public String getDescription() {
return null;
}
@Override
public Object getValue() {
return customDataMap.get(key);
}
@Override
public void setValue(Object value) {
customDataMap.put(key, value);
}
}
public PropertySheetExample {
ObservableList<PropertySheet.Item> list = FXCollections.observableArrayList();
for (String key : customDataMap.keySet())
list.add(new CustomPropertyItem(key));
PropertySheet propertySheet = new PropertySheet(list);
VBox.setVgrow(propertySheet, Priority.ALWAYS);
getChildren().add(propertySheet);
}
}
这种行为可以通过两种方式进一步扩展。首先,现有编辑器可用于默认属性编辑器工厂不支持的类型。以下示例设置新的属性编辑器工厂,它将为 List 类型创建 ChoiceBox。对于其他类型,它将编辑器创建委托给默认工厂。
SimpleObjectProperty<Callback<PropertySheet.Item, PropertyEditor<?>>> propertyEditorFactory = new SimpleObjectProperty<>(this, "propertyEditor", new DefaultPropertyEditorFactory());
propertySheet.setPropertyEditorFactory(new Callback<PropertySheet.Item, PropertyEditor<?>>() {
@Override
public PropertyEditor<?> call(PropertySheet.Item param) {
if(param.getValue() instanceof List) {
return Editors.createChoiceEditor(param, (List) param.getValue());
}
return propertyEditorFactory.get().call(param);
}
});
最后,我们可以创建自定义编辑器并覆盖getPropertyEditorClass()
方法从属性表.项目 http://controlsfx.bitbucket.io/org/org/controlsfx/control/PropertySheet.Item.html返回自定义编辑器类型。在这种情况下,默认的属性编辑器工厂将创建编辑器,并且无需重写工厂方法。