【问题标题】:How can I implement an interface in my JavaFX Controller?如何在我的 JavaFX 控制器中实现接口?
【发布时间】:2017-08-15 15:40:36
【问题描述】:

我有一个用于将系统消息发布到 GUI 的接口,但我这样做的方式会导致尝试使用接口方法的类(而不是实现它的方法)出现 NULL POINTER EXCEPTION

public interface SystemMessage {
    void postMessage(String outText);
}

在我的控制器中,我实现了这个接口并使用它向 GUI 发布消息

public class MainController implements SystemMessage {
    @FXML
    public DialogPane systemMessage;

    @Override
    public void postMessage(String outText) {
        systemMessage.setContentText(outText);
    }
}

我从 Main.java 调用一些辅助类来做一些后台工作(我还没有线程化所以借口一切都在主线程上)

@Override
public void start(Stage primaryStage) throws Exception{
    FXMLLoader loader = new FXMLLoader(getClass().getResource("fxml/entry.fxml"));
    Parent root = loader.load();
    this.mainController = loader.getController();
    primaryStage.setTitle("Title");
    primaryStage.setScene(new Scene(root, 300, 275));
    primaryStage.show();
    initializeSync();
}

private void initializeSync() {
    //Each of these perform several function on initialization
    Identity identity = new Identity();
    String[] args = null;
    Api api = new Api();
    api.Get(args);
    SqLite db = new SqLite();
}

所以,在我的 Identity Class 初始化时,我尝试使用接口发布消息,但我得到 NULL POINTER EXCEPTION。

public class Identity {
    private String machineId = null;
    public String statusText = null;

    SystemMessage systemMessage;// Trying to instantiate the system message interface??

    public Identity(){
        systemMessage.postMessage("Checking Machine Identity");
        //..//
    }
    //..//
}  

【问题讨论】:

    标签: java class javafx interface


    【解决方案1】:

    我不确定您的问题是否特定于 JavaFX。

    您需要在创建Identity 对象时将依赖项设置为SystemMessage
    替换:

    Identity identity = new Identity();
    

    作者:

    ...
    MainController mainController = ... // retrieve it with fxmlLoader if required
    Identity identity = new Identity(mainController);
    

    并更改Identity 构造函数,使其接受SystemMessage 参数:

    public Identity(SystemMessage systemMessage){
        this.systemMessage = systemMessage;
        systemMessage.postMessage("Checking Machine Identity");
    }
    

    【讨论】:

    • 感谢您的回复。我正在努力理解。因此,我需要引用附加了控制器的 fxmlloader 并将其传递给 Identity 类,以便它知道在哪里或如何使用该接口?
    • 另外,请参阅我的编辑。在我的主文件中,我有一个在 start() 中设置的 mainController 对象。我可以在整个 main 中使用它来传递给每个实例化的类吗?
    • 我想通了...我能够在我的 start() 方法中使用您的代码,然后将(“reference”?)传递给其他类!!!谢谢!!!
    • 不客气。在您进行编辑之前,我不知道您是否有一个变量在 initializeSync() 方法的范围内引用了 MainController 对象。因此,在我的回答中,我首先检索了它。但是正如你所拥有的那样,你只需要确实使用它:)我会在我的回答中明确指出这一点。
    【解决方案2】:

    当@silversunhunter 正确回答时,将实际的mainController 传递到Identity

        initializeSync(this.mainController);
    }
    
    private void initializeSync(SystemMessage systemMessage) {
        Identity identity = new Identity(systemMessage);
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-10-28
      • 2023-02-09
      • 1970-01-01
      • 1970-01-01
      • 2016-10-20
      • 1970-01-01
      相关资源
      最近更新 更多