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

2017/3/27

Accessing getter method

ironphoenix20 ironphoenix20

2017/3/27

#
Here is one class CriticalBar I have that needs to access the variable returned from a getter method in another class HealthBar
/**
     * Creates a new image with text saying "Low Energy Remaining" and sets it to the CriticalBar actor
     */
    public CriticalBar()
    {
       bar = new GreenfootImage("LOW ENERGY REMAINING! " + HealthBar.getHp(), 20, Color.RED, new Color(0,0,0,0));
       this.setImage(bar);
    }
but now it says "non static method getHp() cannot be referenced from a static context." how can i fix this so that i can display the current Hp of the HealthBar on the CriticalBar actor?
Nosson1459 Nosson1459

2017/3/28

#
You should have a getter method in you World for getting the HealthBar instance that's being used in the scenario. You'll have to access the correct world after the CriticalBar has been added, then you can do (in CriticalBar):
/**
 * This method is called by the Greenfoot system when this actor has been
 * inserted into the world. This method can be overridden to implement
 * custom behavior when the actor is inserted into the world.
 * <p>
 * The default implementation does nothing.
 *
 * @param world The world the object was added to.
 */
protected void addedToWorld(World world) {
    bar = new GreenfootImage("LOW ENERGY REMAINING! " + ((WorldName)getWorld()).getHealthBar().getHp(), 20, Color.RED, new Color(0, 0, 0, 0)); // use correct world name
    setImage(bar);
}
ironphoenix20 ironphoenix20

2017/3/28

#
Also, i reopened greenfoot and now my HealthBar class is saved as an "other class" rather than an "Actor class" and im unable to move it. what do i do?
danpost danpost

2017/3/28

#
ironphoenix20 wrote...
Also, i reopened greenfoot and now my HealthBar class is saved as an "other class" rather than an "Actor class" and im unable to move it. what do i do?
Make sure the class extends the Actor class -- or post the entire class here for inspection.
ironphoenix20 ironphoenix20

2017/3/28

#
the healthbar class is moved to other classes from actor classes for some reason and the "extends Actor" code is shown as an error. why might this be?
danpost danpost

2017/3/28

#
ironphoenix20 wrote...
the healthbar class is moved to other classes from actor classes for some reason and the "extends Actor" code is shown as an error. why might this be?
Try this. Copy the code of the class onto your clipboard (Ctrl-A followed by Ctrl-C). Then remove the class and create a new subclass of Actor to paste the code back into (Ctrl-A followed by Ctrl-V).
danpost danpost

2017/3/28

#
Make sure the class still has this for its first line:
import greenfoot.*;
Another try would be to close and re-open greenfoot again.
You need to login to post a reply.