在屏幕之间传递参数的错误Java FXML

时间:2016-04-02 09:38:46

标签: java java-8 javafx-2 fxml

当我尝试在屏幕之间传递参数时,我遇到了一些问题

这是我的LogIn控制器:

   @FXML
public void handleButtonAction(ActionEvent event) throws IOException{
    String text = textFieldLogIn.getText();
    Stage stage = new Stage();

    if(text.length() != 0){

        FXMLLoader fxmlLoader = new FXMLLoader(getClass().getResource("Menu.fxml"));
        MenuController controller = fxmlLoader.<MenuController>getController();
        Parent root = (Parent)fxmlLoader.load(); 

        stage = (Stage) btnLogIn.getScene().getWindow();

        detail.setName("Tu");
            controller.setDetail(detail);

        Scene scene = new Scene(root);
        stage.setScene(scene);


        stage.show();
    }
    else{
        notiLogIn.setText("Please enter your name");
        notiLogIn.setTextFill(Color.RED);
    }

这是我的班级CustomerDetails:

public class CustomerDetails {
String name;

public String getName() {
    return name;
}

public void setName(String name) {
    this.name = name;
}

public int getAttendance() {
    return attendance;
}

public void setAttendance(int attendance) {
    this.attendance = attendance;
}

public double getTotalBill() {
    return totalBill;
}

public void setTotalBill(double totalBill) {
    this.totalBill = totalBill;
}
int attendance;
double totalBill;

这是我的MenuController:

public class MenuController implements Initializable {
  CustomerDetails detail = new CustomerDetails();

public CustomerDetails getDetail() {
    return detail;
}

public void setDetail(CustomerDetails detail) {
    this.detail = detail;
}
@FXML
private AnchorPane menuPane;
@FXML
private SplitPane menuSplitPane;
@FXML
private AnchorPane menuPane1;
@FXML
private VBox menuVBox;
@FXML
private Button btnFood;
@FXML
private Button btnDrink;
@FXML
private Button btnOther;
@FXML
private Button btnBill;
@FXML
private Label menuWelcome;
@FXML
private AnchorPane displayMenu;

所以现在我遇到的问题是,当我使用带控制器的getController()时,我遇到了一个关于java.lang.NullPointerException的错误,我无法将值传递给屏幕2:菜单。那么我应该解决这个问题呢?

1 个答案:

答案 0 :(得分:0)

The question is not about parameter passing. You got a NullPointerException because controller is null, not because details is null.

Here you get the controller with getController before you call load.

FXMLLoader fxmlLoader = new FXMLLoader(getClass().getResource("Menu.fxml"));
MenuController controller = fxmlLoader.<MenuController>getController();
Parent root = (Parent)fxmlLoader.load();

The load method loads the object hierarchy from an FXML document and also this method creates an controller object for you which can be retrieved by getController().

Solution: get the controller after you have loaded the FXML file:

FXMLLoader fxmlLoader = new FXMLLoader(getClass().getResource("Menu.fxml"));
Parent root = (Parent)fxmlLoader.load();
MenuController controller = fxmlLoader.<MenuController>getController();