我正在尝试将变量从一个 Controller 传输到另一个 Controller ,但我没有得到正确的输出:
我的代码:
public class CustomControl extends AnchorPane implements Initializable {
String customId;
public CustomControl() {
//if you want to set a FXML
FXMLLoader fxmlLoader = new FXMLLoader(getClass().getResource("/res/customControl.fxml"));
//Defines this class as the controller
fxmlLoader.setRoot(this);
//this.getStylesheets().add("/res/style.css"); <- if you want to set a css
fxmlLoader.setController(this);
try {
fxmlLoader.load();
} catch (IOException exception) {
throw new RuntimeException(exception);
}
}
public String getCustomId() {
return customId;
}
public void setCustomId(String customId) {
return this.customId = customId;
}
@Override
public void initialize(URL arg0, ResourceBundle arg1) {
//Initializes the controller
}
}
在其他 Controller 上设置 CustomId 变量
CustomControl c = new CustomControl();
c.setCustomId("StackOverflow");
从其他 Controller 获取 CustomId 变量
CustomControl c = new CustomControl();
c.getCustomId();
System.out.Println(c.getCustomId());
它给了我输出
null
但必需的是
StackOverflow
我知道已经有人问过同样的问题 Link因此,不要将其标记为重复
因为 在我的问题中,firstcontroller.java 有两个 Controller
CustomControl c = new CustomControl();
c.setCustomId("StackOverflow");
现在在 secondarycontroller.java
CustomControl c = new CustomControl();
c.getCustomId();
System.out.Println(c.getCustomId());
因为我们在不同的 Controller 中获取设置数据,所以它给了我输出
null
请帮帮我。 谢谢。
最佳答案
在 secondarycontroller.java 中,您正在实例化一个新对象,c。
CustomControl c = new CustomControl();
c.getCustomId();
System.out.Println(c.getCustomId());
此不引用firstcontroller.java中的同名对象。如果您希望在 firstcontroller.java 中实例化对象 c,则需要将其传递到 secondcontroller.java 那里访问它。
关于javafx 变量在两个 Controller 之间传输数据(在不同 Controller 中设置和获取数据)- 已更新,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24209773/