如何在JavaFX Controller中实现接口?

时间:2017-08-15 15:40:36

标签: java class javafx interface

我有一个用于将系统消息发布到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("ASI Sync!");
    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");
        //..//
    }
    //..//
}  

2 个答案:

答案 0 :(得分:1)

我不确定您的担忧是否与JavaFX有关。

创建SystemMessage对象时,需要将依赖关系设置为Identity 替换:

Identity identity = new Identity();

by:

...
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");
}

答案 1 :(得分:1)

正如@silversunhunter正确回答,将实际mainController传递给Identity

    initializeSync(this.mainController);
}

private void initializeSync(SystemMessage systemMessage) {
    Identity identity = new Identity(systemMessage);