[英][JavaFX-Scenebuilder][Custom Controller] Load error in Scenebuilder
[英]Error when trying to pass a variable to another controller in javafx/scenebuilder
我正在做一個簡單的程序,其中我試圖將一個TextField中的字符串添加到另一個場景中的ListView中。 問題是當我將字符串傳遞給將其添加到列表的方法時,我得到了NullPointerException。
這是主要場景的控制器代碼:
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();
}
}
這是列表場景的控制器的代碼:
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);
}
}
我需要做什么來修復它? 如果我可以添加的話,是否可以在另一個階段/場景中將變量添加到ListView(或任何其他文本容器)而無需打開包含它的階段/場景,當您打開它時,您會看到添加的內容嗎? 如果是這樣,我需要添加什么?
因為您正在調用getController()
方法,並且未在Java源代碼中設置控制器,所以必須在fxml文件中定義控制器。 您可以發布fxml源代碼嗎?
在fxml中,您的根元素應將fx:controller屬性設置為控制器的類路徑,例如:
fx:controller="com.class.path.to.ListController
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.