我正在编写一个有许多数据输入窗口的应用程序,每个窗口都有一个系统消息标签。
我有一个用于通用方法的 GenUtil 类,其中之一在调用该方法的 Controller 中设置系统消息。
如果我将 Controller 引用传递给方法 ie,则设置系统消息有效。
加载 FXML 时创建对数据输入窗口 Controller 的引用:
deWindowController = loader.getController();
在数据输入窗口 Controller 中:
genUtil.setSystemMessage(this);
在 GenUtil 中:
public void setSystemMessage(FXMLDEWindowController deWindowController) {
deWindowController.lblSysMsg.setText("setting the message");
}
但是,setSystemMessage 方法将从许多 FXML Controller 调用,我不知道如何“通用化”这个过程。
1) 方法参数中的内容:
public void setSystemMessage(**<WHAT_GOES_HERE?>** controllerRef) {
2)假设系统消息标签ID都是lblSysMsg,是否可以像以前一样使用controllerRef设置消息标签?
我可以在 GenUtil 类中包含对所有 Controller 的引用,并且在每个 Controller 中,在我调用 setSystemMessage 方法时传递一个包含数据输入窗口名称的字符串。这样我就可以手动确定要使用的 Controller 。但是,我正在努力避免这种情况。
有人可以帮忙吗?
我正在使用 JavaSE8 和 NetBeans8.2。
最佳答案
您不应提供对字段的直接访问。这将允许该类的用户处理该字段,包括将其设置为 null
或修改 text
属性以外的属性。
在 Controller 的通用父类(super class)型中声明一个setSystemMessage
方法。如果所有 Controller 都包含相同的字段,抽象类将是避免重复的不错选择,但您也可以使用接口(interface)。
使用这个父类(super class)型作为 controllerRef
参数的类型:
public void setSystemMessage(SuperType controllerRef) {
controllerRef.setSystemMessage("setting the message");
}
public abstract class SuperType {
@FXML
private Label lblSysMsg;
public void setSystemMessage(String message) {
lblSysMsg.setText(message);
}
}
关于java - 是否有将 FXML Controller 引用作为参数传递给方法的通用方法?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51492914/