使用引用从Controller外部更改FXML元素 - NullPointerException

时间:2016-04-15 07:14:44

标签: javafx reference controller fxml

我想通过使用我在main函数中创建的引用来从Controller类外部更改FXML元素的文本,但是我得到了NullPointerException。

班长控制器:

public class Controller implements Initializable {

    @FXML
    public ComboBox<String> comboBoxSelectPort;

    @Override
    public void initialize(URL url, ResourceBundle rb) {

        Language l = new Language(); 
        l.setLanguage();

        comboBox.setPromptText("New Text");   // This works!
    }
}

班级语言:

public class Language {

    private Controller c = Main.controller;

    public void setLanguage(){

        c.comboBox.setPromptText("New Text");   // This is NOT working!
    }
}

更新1:

班级主要:

public class Main extends Application {

    public static Stage stage;
    public static Controller controller;
    @Override
    public void start(Stage stage) throws Exception {

        FXMLLoader loader = new FXMLLoader(getClass().getResource("Scene.fxml"));
        Parent root = (Parent) loader.load();
        controller = (Controller) loader.getController();
        System.out.println(controller);           // Works!
        ....

但在Controller或语言课程中

System.out.println(Main.controller);     // Output: Null

更新2:

问题似乎是,在主要创建控制器的过程中创建了控制器。

1 个答案:

答案 0 :(得分:0)

将控制器引用传递给Language实例:

public class Language {

    private final Controller c ;

    public Language(Controller controller) {
        this.c = controller ;
    }

    public void setLanguage(){

        c.comboBox.setPromptText("New Text");   // This is NOT working!
    }
}

然后

public class Controller implements Initializable {

    @FXML
    public ComboBox<String> comboBoxSelectPort;

    @Override
    public void initialize(URL url, ResourceBundle rb) {

        Language l = new Language(this); 
        l.setLanguage();

        comboBox.setPromptText("New Text");   // This works!
    }
}