大家晚上好,
我已经发现了很多关于这个话题的帖子,但是我仍然无法将一个对象从Controller1传递到Controller2。是否有完整的教程或一些示例项目可以做到这一点?
我已经走到了这一步,但卡住了:
Country类
public class Country {
private SimpleStringProperty country = new SimpleStringProperty("");
//Constructor
public Country() {
}
//GETTERS
public String getCountry() {
return country.get();
}
//SETTERS
public void setCountry(String value) {
country.set(value);
}
@Override
public String toString() {
return getCountry();
}
}
当程序启动时,主FXML文件会被加载(Sample.fxml)。其中包含一个边框面板,在顶部面板中有一个菜单栏,在中心有一个内容面板。在初始化时,我创建了一个新的Country对象并将其存储在全局变量中。我有一个方法,当点击菜单项时,可以将另一个FXML文件加载到内容面板中: SampleController.java
public class SampleController implements Initializable {
@FXML
private Pane pContent;
private Country c;
@FXML
private void handleButtonAction(ActionEvent event) throws IOException {
System.out.println(c); //this prints Belgium, which is correct
URL url = getClass().getResource("Sub1.fxml");
FXMLLoader fxmlloader = new FXMLLoader();
fxmlloader.setLocation(url);
fxmlloader.setBuilderFactory(new JavaFXBuilderFactory());
pContent.getChildren().clear();
pContent.getChildren().add((Node) fxmlloader.load(url.openStream()));
}
@Override
public void initialize(URL url, ResourceBundle rb) {
c = new Country();
c.setCountry("Belgium");
}
public Country getCountryFromSampleController(){
return c;
}
}
现在我希望在加载Sub1.fxml时捕获Country对象,这意味着我需要在initialize()中获取该国家对象。
Sub1Controller.java
public class Sub1Controller implements Initializable {
/**
* Initializes the controller class.
*/
@Override
public void initialize(URL url, ResourceBundle rb) {
SampleController sp = new SampleController(); //I don't know how to fetch the original SampleController object
System.out.println(sp.getCountryFromSampleController());
//this prints null, which is ofcourse logical because I make a new SampleController object.
}
}
我有一个问题,如何获取“原始”的SampleController对象,以便可以使用getCountryFromRoot()方法来获取值为比利时的Country对象?我已经在StackOverflow上搜索了几个小时,并阅读了每篇帖子,但似乎我找不到缺失的链接...任何帮助(最好是使用此代码)都将不胜感激!对于这篇长文,我很抱歉,我试图尽可能详细,否则我将永远无法理解...