javafx变量之间的数据传输两个控制器(设置和获取数据在不同的控制器)-更新



我正试图将变量从一个控制器转移到另一个控制器,但我没有得到正确的输出:

我的代码:

   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
    }
}

在其他控制器上设置CustomId变量

CustomControl c = new CustomControl();
c.setCustomId("StackOverflow");

从其他控制器获取CustomId变量

CustomControl c = new CustomControl();
c.getCustomId();
System.out.Println(c.getCustomId());

输出

null

但必须是

StackOverflow

我知道已经有人问过同样的问题了Link所以,不要把它标记为重复的

因为

在我的问题中有两个控制器在firstcontroller.java

 CustomControl c = new CustomControl();
    c.setCustomId("StackOverflow");

secondcontroller.java

CustomControl c = new CustomControl();
c.getCustomId();
  System.out.Println(c.getCustomId());

因为我们在不同的控制器中获取设置数据所以它给了我输出

null

请帮帮我。谢谢你。

在secondcontroller.java中,您正在实例化一个新的对象c。

CustomControl c = new CustomControl();
c.getCustomId();
  System.out.Println(c.getCustomId());

这个引用firstcontroller.java中的同名对象。如果您希望在firstcontroller.java中实例化对象c,则需要将其传递给secondcontroller.java

最新更新