javafx 变量在两个 Controller 之间传输数据(在不同 Controller 中设置和获取数据)- 已更新

标签 java javafx javafx-2 javafx-8

我正在尝试将变量从一个 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/

相关文章:

java - 为什么我的冒泡排序无法对对象数组进行排序?

java - 最小化和最大化 Java Swing 中自定义事件的 JFrame

Android 2.2 上的 JavaFX - 无效包

java - 如何使 TextField 填充包含多个节点的 Pane 的所有剩余宽度?

JavaFX - 监听列表中的变化

java - 签名属性: Fx Build Configuration

java - 我该如何解决这个 Java 继承问题?

java - 可以在 JSP EL 中指定对 isAttribute 与 getAttribute 的访问吗?

Java FX 2 堆空间

javafx-2 - 始终显示 JavaFX ListView 的垂直滚动条