When passing an object from a class to another, it's reset to initial values in the receiving class

huangapple go评论59阅读模式
英文:

When passing an object from a class to another, it's reset to initial values in the receiving class

问题

我正在使用JavaFX创建一个GUI,SenderReceiver 类都是FXML文件的控制器。

我尝试将一个 Ball 对象从一个类传递到另一个类,但在接收类中它被重置为初始值。

这是我的代码:

class Sender {
    void method{
        Ball ball = new Ball("RED");
        Receiver receiver = new Receiver();
        receiver.setBall(ball);
    }
}
class Receiver {
    Ball ball = new Ball();

    public Receiver(){ };

    void setBall(Ball senderBall){
        this.ball = senderBall;
    }

    // 使用按钮来检查
    void testDisplay(){
        System.out.println("the ball color IS :" + ball.color);
        // 它打印出了Ball的默认颜色,而不是我从"Sender"类传递的RED颜色
    }
}
英文:

I'm making a GUI using javafx, both Sender and Receiver classes are controllers for fxml files.

I trying to pass a Ball object from a class to another, but it's reset to initial values in the receiving class.

This is my Code:

    class Sender {
    
     void method{
     Ball ball = new Ball("RED");
     Receiver receiver = new Receiver();
     receiver.setBall(ball);
     }
    
    }

    class Receiver {
    
    Ball ball = new Ball();
    
    public Receiver(){ };
    
    void setBall(Ball senderBall){
    this.ball = senderBall;
    }
    // using a button to check
    void testDisplay(){
    System.out.println("the ball color IS :"+ ball.color);
// it prints out the default color of the Ball, not the color RED that i passer from the class "Sender"
    }
    }

答案1

得分: 1

Script is great-written, but you forgot to call void method() in your testDisplay() void from class Sender

void testDisplay(){    
    Sender send = new Sender();
    send.method();
    System.out.println("the ball color IS :" + ball);
}
英文:

Script is great-written, but you forgot to call void method() in your testDisplay() void from class Sender

void testDisplay(){    
    Sender send = new Sender();
    send.method();
    System.out.println("the ball color IS :"+ ball);
}

huangapple
  • 本文由 发表于 2020年8月8日 20:01:04
  • 转载请务必保留本文链接:https://go.coder-hub.com/63315129.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定