简体   繁体   中英

Error when trying to pass a variable to another controller in javafx/scenebuilder

I'm making a simple program wherein I am trying to add a string from a TextField to a ListView in another scene. The problem is I am getting a NullPointerException when I pass the string to the method which will add it to the List.

Here is the code for controller for the main scene:

import java.io.IOException;
import javafx.event.ActionEvent;
import javafx.fxml.FXML;
import javafx.fxml.FXMLLoader;
import javafx.scene.Parent;
import javafx.scene.Scene;
import javafx.scene.control.TextField;
import javafx.stage.Stage;

public class MainPageController {

@FXML TextField txtfield;

public void addButton(ActionEvent event) {

    String a=txtfield.getText();
    FXMLLoader loader= new FXMLLoader();
    loader.setLocation(getClass().getResource("/progra/view/ListView.fxml"));
    ListController obj=loader.getController();
    obj.addList(a);// <----NullPointerException

}

public void openList(ActionEvent event) throws IOException {

    FXMLLoader fxmlLoader = new FXMLLoader(getClass().getResource("/program /view/ListView.fxml"));
    Parent root1 = (Parent) fxmlLoader.load();
    Stage stage = new Stage();
    stage.setScene(new Scene(root1));  
    stage.show();

}
}

Here is the code for the controller of the list scene:

import javafx.fxml.FXML;
import javafx.scene.control.ListView;

public class ListController{

@FXML
ListView<String> listofstrs;

public void addList(String a) {

    listofstrs.getItems().add(a);

}
}

What do I need to do to fix it? If I may add, is it possible to add variables to a ListView (or any other text containers) in another stage/scene without opening the stage/scene where it is contained, and when you open it you will see the things you added? If so, what do i need to add?

Because you are calling the getController() method, and the controller is not set within the Java source, you must have the controller defined within your fxml file. Can you post the fxml source?

In your fxml, your root element should have the fx:controller attribute set to the class path of the controller, eg:

fx:controller="com.class.path.to.ListController

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM