各位晚上好,
我已经找到了大量关于此主题的帖子,但是我仍然无法设法将对象从Controller1传递到Controller2。是否有某个完整的教程或一些示例项目可以做到这一点?
我已经走了这么远,直到被卡住:
国家级
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()上获取country对象:
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的每篇文章,但是看来我找不到丢失的链接...感谢任何帮助(最好是使用此代码)!
很长的帖子,很抱歉,我试图尽可能完整,否则我将永远无法理解...
BIG阳
暮色呼如
相关分类