我正在编写一个应用程序,它将有许多数据输入窗口,每个窗口都有一个系统消息标签。
我有一个通用方法的 GenUtil 类,其中一个在调用该方法的 Controller 中设置系统消息。
如果我将 Controller 引用传递给方法,即设置系统消息有效。
在加载 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
以外的属性属性(property)。
声明 setSystemMessage
Controller 的通用父类(super class)型中的方法。如果所有 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/