【发布时间】:2019-09-09 07:16:08
【问题描述】:
我用 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();
}
}
非常感谢您的帮助:)
【问题讨论】:
-
请使用minimal reproducible example 更新您的问题。目前尚不清楚您要做什么。
-
当您在
setscene()中进行测试打印输出时,请检查root是否不为空。 -
与您的问题无关:请学习 java 命名约定并遵守它们。
标签: java button javafx controller scenebuilder