This site requires JavaScript, please enable it in your browser!
Greenfoot back
Eddir
Eddir wrote ...

2014/1/21

Help with changing a Subclasses image

Eddir Eddir

2014/1/21

#
I've got a subclass which I want to change image depending on a variable from its Class. It's to change the image of a throttle indicator but it isn't changing. I inspected the currentSpeed variable from the subclass where it is 0 and the class which it is written in where it changes as expected. An help will be greatly appreciated.
public void imageState()
    {
        if (currentSpeed == 0)
        {
            this.setImage("Idle throttle.png");
        }    
        
        if (currentSpeed == 2)
        {
            this.setImage("Low throttle.png");
        }    
        
        if (currentSpeed == 4)
        {
            this.setImage("Mid throttle.png");
        }    
        
        if (currentSpeed == 6)
        {
            this.setImage("Full throttle.png");
        }    
    }
davmac davmac

2014/1/21

#
Maybe post the whole code for the subclass. It sounds like you might be redefining the variable instead of using the variable from the superclass. Another possibility is that you have two different objects and are only changing the variable value in one of them (making something a subclass of something else doesn't let one object see another's variable values automatically). In short: post more code!
Eddir Eddir

2014/1/21

#

public class ThrottleState extends Plane
{
    
    public void act() 
    {
        imageState();
    }    
    
    public void imageState()
    {
        if (currentSpeed == 0)
        {
            this.setImage("Idle throttle.png");
        }    
        
        if (currentSpeed == 2)
        {
            this.setImage("Low throttle.png");
        }    
        
        if (currentSpeed == 4)
        {
            this.setImage("Mid throttle.png");
        }    
        
        if (currentSpeed == 6)
        {
            this.setImage("Full throttle.png");
        }    
    }
}
import greenfoot.*; 
public class Plane extends Actor
{
    public int gConstant = 0;
    public int currentSpeed = 0;
    
    public void act() 
    {
    }  
   
}
davmac davmac

2014/1/21

#
Why does ThrottleState extend Plane? that seems wrong. A ThrottleState is not a Plane. I'm guessing that you've got two objects - one is a Plane, and the other is a ThrottleState - and that you're setting the currentSpeed of the Plane, and expecting that to carry through to the ThrottleState? It doesn't work that way. Each object has their own copy of the variable. Your ThrottleState needs to get the speed from the plane somehow. See for example tutorial #6 which deals with this precise problem.
Eddir Eddir

2014/1/21

#
Okay, thanks for your help.
You need to login to post a reply.