首页 > 解决方案 > 为什么从另一个控制器调用的方法不会改变场景?

问题描述

我用 firstController 获得了场景 first.fxml,它是 BorderPane,左侧有一个按钮(birthCert)。

当我单击按钮(birthCert)时,我成功地将 second.fxml 加载到 BorderPane 的中心。

    @FXML
    void birthCert(ActionEvent event) {

        Parent root;
        try {
            root = load(getClass().getResource("second.fxml"));
            id_borderPane.setCenter(root);

        } catch (IOException e) {
            e.printStackTrace();
        }

    }

second.fxml 与 secondController 类连接,并有 1 个按钮(sendRequest)。单击此按钮时,我创建了 firstController 的实例,并且我希望调用方法 setscene 将third.fxml 加载到borderPane 的中心。

third.fxml 仅显示消息“您的请求已发送”。

问题是,当我使用 firstController 的实例调用 secondController 类中的方法 setscene

c.setscene();
 public void setscene() {
        Parent root;
        try {
            root = load(getClass().getResource("third.fxml"));
            id_borderPane.setCenter(root);

        } catch (IOException e) {
            e.printStackTrace();
        }
    }

它不会将 third.fxml 加载到 BorderPane 的中心,只是 second.fxml 保持加载状态,什么都没有发生。

我尝试了控制打印,我测试了 root 是否为空,但打印工作正常且 root 不为空,所以我真的不明白是什么原因导致它在 BorderPane 中心不显示third.fxml

这是整个代码:

package controllers;

import static javafx.fxml.FXMLLoader.load;
import java.io.IOException;
import javafx.event.ActionEvent;
import javafx.fxml.FXML;
import javafx.scene.Parent;
import javafx.scene.control.Button;
import javafx.scene.layout.BorderPane;

public class firstController {

    @FXML
    private BorderPane id_borderPane;

    @FXML
    void birthCert(ActionEvent event) {

        Parent root;
        try {
            root = load(getClass().getResource("second.fxml"));
            id_borderPane.setCenter(root);

        } catch (IOException e) {
            e.printStackTrace();
        }

    }

    public void setscene() {
        Parent root;
        try {
            root = load(getClass().getResource("third.fxml"));
            id_borderPane.setCenter(root);

        } catch (IOException e) {
            e.printStackTrace();
        }   
    }

}
package controllers;

import java.io.IOException;

import javafx.fxml.FXML;
import javafx.fxml.FXMLLoader;
import javafx.scene.Parent;
import javafx.scene.control.TextArea;
import javafx.scene.input.MouseEvent;

public class secondController{

    @FXML
    void SendRequset(MouseEvent event) throws IOException  {

        FXMLLoader loader = new FXMLLoader(getClass().getResource("first.fxml"));
        loader.load();
        UserGUISendReqController c = loader.getController(); // instance of firstController
        c.setscene();
    }
}

非常感谢您的帮助:)

标签: javabuttonjavafxcontrollerscenebuilder

解决方案


你有:

FirstController
|- SecondController

然后在第二个控制器中单击按钮以添加您正在执行的第三个控制器

FirstController
|- SecondController
   |- new FirstController.setScene()

您应该实例化一个新的 FirstController,您应该调用 SecondController 父级,或者以某种方式将 FirstController 的引用传递给第二个控制器。

您想在 SecondController 上使用 getParent 或将活动的 FirstController 传递给 SecondController 的其他方法,这样当您调用它时,它就是正确的。

附言。人们还会评论您的命名约定不符合标准。


推荐阅读