从javafx中的另一个类访问窗格

时间:2017-02-06 10:29:12

标签: javafx

我无法从另一个类访问,我在一个FXML文件中创建了两个不同控制器的窗格,第二个窗格必须在第一个窗格中移动,在Click Action上,我在第二个窗格中加载了一个FXML文件,也成功地移动了一次窗格,但第二次我想从第二个控制器移动它,但是它给了我一个NullPointerException。

这是我移动窗格的主控制器:

public class MainController implements Initializable {

@FXML
private Pane searchPane;
@FXML
private Pane secondPane; 

private TranslateTransition nextTransition;

public Pane getSecondPane() {
    return secondPane; // Accessing Pane with this getter method
}

/**
 * Initializes the controller class.
 */
@Override
public void initialize(URL url, ResourceBundle rb) {

}    

@FXML
private void nextBtnAction(ActionEvent event) {
    try {
        Parent pessFxml =  FXMLLoader.load(getClass().getResource("firstPane.fxml"));
        secondPane.getChildren().add(pessFxml);
        nextTransition = new TranslateTransition(Duration.millis(300), secondPane);
        nextTransition.setToX(searchPane.getLayoutX()-secondPane.getLayoutX());
        nextTransition.play();
    } catch (IOException ex) {
        JOptionPane.showMessageDialog(null, "Form does not found" ,ex.toString(),0);
    }
}

}

这是SecondController我正在访问该窗格以便顺利地将其移回,但是它正在抛出NullPointerException: 请告诉我如何解决这个问题

public class SecondController implements Initializable {

MainController mainControll;


/**
 * Initializes the controller class.
 */
@Override
public void initialize(URL url, ResourceBundle rb) {

}

@FXML
private void backBtnPessAction(ActionEvent event) {
    //here i am putting the second pane to move back
    TranslateTransition back = new TranslateTransition(Duration.millis(300), mainControll.getSecondPane());
    back.setToX(mainControll.getSecondPane().getLayoutX()-750);
    back.play();
}

}

1 个答案:

答案 0 :(得分:0)

MainController永远不会在SecondController中初始化。在nextBtnAction中创建第二个控制器时应该传递它。

MainController代码:

private void nextBtnAction(ActionEvent event) {
    try {
        FXMLLoader loader = new FXMLLoader(getClass().getResource("firstPane.fxml"));
        Parent pessFxml =  loader.load();
        SecondController controller = (SecondController)loader.getController();
        controller.setMainController(this);
        secondPane.getChildren().add(pessFxml);
        nextTransition = new TranslateTransition(Duration.millis(300), secondPane);
        nextTransition.setToX(searchPane.getLayoutX()-secondPane.getLayoutX());
        nextTransition.play();
    } catch (IOException ex) {
        JOptionPane.showMessageDialog(null, "Form does not found" ,ex.toString(),0);
    }
}

SecondController:

public void setMainController(MainController controller) {
    this.mainControll = controller;
}