英文:
When passing an object from a class to another, it's reset to initial values in the receiving class
问题
我正在使用JavaFX创建一个GUI,Sender 和 Receiver 类都是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);
}
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。


评论