[英]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. 我正在做一个简单的程序,其中我试图将一个TextField中的字符串添加到另一个场景中的ListView中。 The problem is I am getting a NullPointerException when I pass the string to the method which will add it to the List.
问题是当我将字符串传递给将其添加到列表的方法时,我得到了NullPointerException。
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?
如果我可以添加的话,是否可以在另一个阶段/场景中将变量添加到ListView(或任何其他文本容器)而无需打开包含它的阶段/场景,当您打开它时,您会看到添加的内容吗? 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. 因为您正在调用
getController()
方法,并且未在Java源代码中设置控制器,所以必须在fxml文件中定义控制器。 Can you post the fxml source? 您可以发布fxml源代码吗?
In your fxml, your root element should have the fx:controller attribute set to the class path of the controller, eg: 在fxml中,您的根元素应将fx:controller属性设置为控制器的类路径,例如:
fx:controller="com.class.path.to.ListController
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.