java - 如何创建一个方法来接受和返回任何类型的 ObjectProperty ?
问题描述
我的应用程序有一个包含多个ObjectProperty<Enum>
字段的对象。我正在尝试编写一个辅助方法来执行以下操作:
- 接受任何类型的
ObjectProperty<Enum>
作为参数 - 显示一个
ChoiceDialog
弹出窗口,允许用户为enum
- 更新
enum
传递的ObjectProperty
本身的值
我对泛型一点也不熟悉,但我相信以下方法可能有效(没有编译器错误):
public static <E extends Enum<E>> boolean editEnumProperty(String prompt,
ObjectProperty<Class<E>> property,
Window owner) {
// Create the dialog to ask for a new enum value
ChoiceDialog<E> dialog = new ChoiceDialog<>();
dialog.setTitle("Edit Value");
dialog.setHeaderText(null);
dialog.setContentText(prompt);
dialog.initOwner(owner);
// Currently, this displays the enum NAME in the ComboBox, rather than it's text value
dialog.getItems().setAll(FXCollections.observableArrayList(property.get().getEnumConstants()));
Stage dialogStage = (Stage) dialog.getDialogPane().getScene().getWindow();
dialogStage.getIcons().add(ImageHelper.appIcon());
Optional<E> result = dialog.showAndWait();
if (result.isPresent()) {
Utility.printTempMsg(result.toString());
Utility.printTempMsg(Enum.valueOf(property.get(), result.toString()).toString());
}
return true;
}
但是,我不确定如何传递ObjectProperty
给这个方法。尝试按如下方式传递我的属性时,出现编译器错误:
linkEditRequestSource.setOnAction(event ->
editEnumProperty(
"Select new Request Source:",
simpleObject.requestSourceProperty(), // <-- no instance(s) of type variable(s) E exist so that RequestSource conforms to Class<E>
lblRequestSource.getScene().getWindow()
)
);
我也不知道ObjectProperty
在用户选择一个之后如何设置值。
下面是一个不工作的 MCVE:
import javafx.application.Application;
import javafx.beans.property.ObjectProperty;
import javafx.beans.property.SimpleObjectProperty;
import javafx.collections.FXCollections;
import javafx.geometry.Insets;
import javafx.geometry.Pos;
import javafx.scene.Scene;
import javafx.scene.control.ChoiceDialog;
import javafx.scene.control.Hyperlink;
import javafx.scene.control.Label;
import javafx.scene.layout.HBox;
import javafx.scene.layout.VBox;
import javafx.stage.Stage;
import javafx.stage.Window;
import java.util.Optional;
enum RequestSource {
ACQUIRED("Acquisition"),
MANUAL("Manually Entered"),
MANAGER("Manager Reported");
private final String text;
RequestSource(String text) {
this.text = text;
}
public String getText() {
return text;
}
}
public class GenericEnumProperty extends Application {
public static void main(String[] args) {
launch(args);
}
public static <E extends Enum<E>> boolean editEnumProperty(String prompt,
ObjectProperty<Class<E>> property,
Window owner) {
// Create the dialog to ask for a new enum value
ChoiceDialog<E> dialog = new ChoiceDialog<>();
dialog.setTitle("Edit Value");
dialog.setHeaderText(null);
dialog.setContentText(prompt);
dialog.initOwner(owner);
dialog.getItems().setAll(FXCollections.observableArrayList(property.get().getEnumConstants()));
Optional<E> result = dialog.showAndWait();
if (result.isPresent()) {
// This should actually set the value of the underlying object's ObjectProperty<RequestSource> to
// the new value selected in the ComboBox
System.out.println(Enum.valueOf(property.get(), result.toString()).toString());
// Will use this value to track which properties have been modified
return true;
}
return false;
}
@Override
public void start(Stage primaryStage) {
// Simple Interface
VBox root = new VBox(10);
root.setAlignment(Pos.CENTER);
root.setPadding(new Insets(10));
// Label to display current value of RequestSource
Label lblRequestSource = new Label();
// Create a new object
SimpleObject simpleObject = new SimpleObject(RequestSource.ACQUIRED);
// Bind the property value to the label
lblRequestSource.textProperty().bind(simpleObject.requestSourceProperty().asString());
// Hyperlink to open value editor
Hyperlink linkEditRequestSource = new Hyperlink("Request Source:");
linkEditRequestSource.setOnAction(event ->
editEnumProperty(
"Select new Request Source:",
simpleObject.requestSourceProperty(), // <-- no instance(s) of type variable(s) E exist so that RequestSource conforms to Class<E>
lblRequestSource.getScene().getWindow()
)
);
root.getChildren().add(
new HBox(5, linkEditRequestSource, lblRequestSource)
);
// Show the stage
primaryStage.setScene(new Scene(root));
primaryStage.setTitle("Sample");
primaryStage.show();
}
}
class SimpleObject {
private final ObjectProperty<RequestSource> requestSourceProperty = new SimpleObjectProperty<>();
public SimpleObject(RequestSource source) {
this.requestSourceProperty.set(source);
}
public RequestSource getRequestSourceProperty() {
return requestSourceProperty.get();
}
public void setRequestSourceProperty(RequestSource requestSourceProperty) {
this.requestSourceProperty.set(requestSourceProperty);
}
public ObjectProperty<RequestSource> requestSourceProperty() {
return requestSourceProperty;
}
}
所以这里真的有一些相关的问题:
- 如何将泛型传递
ObjectProperty<Enum>
给该方法? - 是否可以显示枚举的文本值而不是枚举名称?
Property
用户选择新的后如何设置的值?
解决方案
您需要传递给泛型方法的属性应该是一个ObjectProperty<E>
,而不是一个ObjectProperty<Class<E>>
。然后你可以这样做:
public static <E extends Enum<E>> boolean editEnumProperty(String prompt,
ObjectProperty<E> property,
Window owner) {
// Create the dialog to ask for a new enum value
ChoiceDialog<E> dialog = new ChoiceDialog<>();
dialog.setTitle("Edit Value");
dialog.setHeaderText(null);
dialog.setContentText(prompt);
dialog.initOwner(owner);
dialog.getItems().setAll(property.get().getDeclaringClass().getEnumConstants());
Optional<E> result = dialog.showAndWait();
boolean changed = result.isPresent();
result.ifPresent(property::set);
return changed ;
}
现在您的示例代码按原样工作。
这里有一个警告:如果property.get()
返回null
,那么这将抛出一个空指针异常
dialog.getItems().setAll(property.get().getDeclaringClass().getEnumConstants());
如果要支持值为 null 的“未设置”属性,我认为您需要在方法中添加一个额外的参数来表示类型:
public static <E extends Enum<E>> boolean editEnumProperty(String prompt,
Class<E> enumType,
ObjectProperty<E> property,
Window owner) {
// Create the dialog to ask for a new enum value
ChoiceDialog<E> dialog = new ChoiceDialog<>();
dialog.setTitle("Edit Value");
dialog.setHeaderText(null);
dialog.setContentText(prompt);
dialog.initOwner(owner);
dialog.getItems().setAll(enumType.getEnumConstants());
Optional<E> result = dialog.showAndWait();
boolean changed = result.isPresent();
result.ifPresent(property::set);
return changed ;
}
在这种情况下,您只需要稍作修改:
linkEditRequestSource.setOnAction(event ->
editEnumProperty(
"Select new Request Source:",
RequestSource.class,
simpleObject.requestSourceProperty(),
lblRequestSource.getScene().getWindow()
)
);
你剩下的一个问题是
是否可以显示枚举的文本值而不是枚举名称?
由于并非所有枚举都有getText()
方法,因此没有特别简单的方法可以连接到getText()
您定义的方法以显示枚举值。Function<E, String>
通常,您可以通过重载提供可选参数:
public static <E extends Enum<E>> boolean editEnumProperty(
String prompt,
ObjectProperty<E> property,
Window owner) {
return editEnumProperty(prompt, property, Object::toString, owner);
}
public static <E extends Enum<E>> boolean editEnumProperty(
String prompt,
ObjectProperty<E> property,
Function<? super E, String> displayText,
Window owner) {
// now what...?
}
但由于也无法访问(据我所知) 显示的选择框(或组合框?)ChoiceDialog
,因此没有明显的方法来配置文本的显示方式。
此时您可以滚动您自己的版本ChoiceDialog
(获得对弹出控件的访问权限);例如:
public static <E extends Enum<E>> boolean editEnumProperty(String prompt, ObjectProperty<E> property,
Function<? super E, String> displayText, Window owner) {
Dialog<E> dialog = new Dialog<>();
ChoiceBox<E> choice = new ChoiceBox<>();
choice.setConverter(new StringConverter<E>() {
@Override
public String toString(E object) {
return displayText.apply(object);
}
@Override
public E fromString(String string) {
// Not actually needed...
return null;
}
});
choice.getItems().setAll(property.get().getDeclaringClass().getEnumConstants());
choice.getSelectionModel().select(property.get());
dialog.getDialogPane().setContent(new HBox(5, new Label(prompt), choice));
dialog.getDialogPane().getButtonTypes().setAll(ButtonType.CANCEL, ButtonType.OK);
dialog.setResultConverter(button ->
button == ButtonType.OK ? choice.getSelectionModel().getSelectedItem() : null
);
return dialog.showAndWait().map(value -> {
property.set(value);
return true ;
}).orElse(false);
}
或者您可以尝试像这样的丑陋黑客,它将字符串值和相应的 eval 值存储在 a 中Map
:
public static <E extends Enum<E>> boolean editEnumProperty(String prompt, ObjectProperty<E> property,
Function<? super E, String> displayText, Window owner) {
// Create the dialog to ask for a new enum value
ChoiceDialog<String> dialog = new ChoiceDialog<>();
dialog.setTitle("Edit Value");
dialog.setHeaderText(null);
dialog.setContentText(prompt);
dialog.initOwner(owner);
Map<String, E> displayValueLookup = Stream.of(property.get().getDeclaringClass().getEnumConstants())
.collect(Collectors.toMap(displayText, Function.identity()));
dialog.getItems().setAll(displayValueLookup.keySet());
return dialog.showAndWait()
.map(displayValueLookup::get)
.map(value -> {
property.set(value);
return true ;
})
.orElse(false);
}
现在当然
linkEditRequestSource.setOnAction(event -> editEnumProperty(
"Select new Request Source:",
simpleObject.requestSourceProperty(),
RequestSource::getText,
lblRequestSource.getScene().getWindow()));
推荐阅读
- python - 函数变量不能被使用,因为它没有被声明为变量或找不到
- rust - 如何使用具有闭包成员的结构创建新的关联函数?
- curl - 请求 Autodesk Forge、Reality Capture API 下载链接的错误消息
- python - 从python中的字符串中提取浮点数
- react-native - 如何在不分离的情况下在 android 上使用 react-native 和 expo 共享文件?
- node.js - NodeJS 中的两种 SSL 身份验证
- testflight - TestFlight 发送新的更新通知
- java - 应用程序构造函数中的异常 - 无法启动类
- python - 在 String.replace() 上检查的文档无论如何都不起作用 Python
- c# - 如何在 .Net Core 中使用客户端 SSL 证书