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

2016/1/11

Please help me - Getter doesn't work

TestUser2001 TestUser2001

2016/1/11

#
Hello, I have a big problem, please help me! My world class is Game and the name of the other class is Countdown. I used these codes:
1
2
3
4
5
private String countdown = "00:00";
 
public String getCountdownTime() {
        return countdown;
    }
then my Countdown class:
1
2
3
4
5
6
7
8
9
10
private Game game;
    
   public Countdown() {
       game = (Game) getWorld();
       addPicture();
   }
    
   public void addPicture() {
       setImage(new GreenfootImage( "Countdown: " + game.getCountdownTime(), 20, Color.YELLOW, Color.BLACK ) );
   }
but if I'm compiling this, it gives me a nullpointerexception.. Stacktrace:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
java.lang.NullPointerException
    at Countdown.addPicture(Countdown.java:15)
    at Countdown.<init>(Countdown.java:10)
    at Game.<init>(Game.java:26)
    at sun.reflect.NativeConstructorAccessorImpl.newInstance0(Native Method)
    at sun.reflect.NativeConstructorAccessorImpl.newInstance(NativeConstructorAccessorImpl.java:62)
    at sun.reflect.DelegatingConstructorAccessorImpl.newInstance(DelegatingConstructorAccessorImpl.java:45)
    at java.lang.reflect.Constructor.newInstance(Constructor.java:422)
    at greenfoot.core.Simulation.newInstance(Simulation.java:607)
    at greenfoot.platforms.ide.WorldHandlerDelegateIDE$4.run(WorldHandlerDelegateIDE.java:445)
    at greenfoot.core.Simulation.runQueuedTasks(Simulation.java:494)
    at greenfoot.core.Simulation.maybePause(Simulation.java:299)
    at greenfoot.core.Simulation.runContent(Simulation.java:212)
    at greenfoot.core.Simulation.run(Simulation.java:205)
I don't know why.. Please help me! Sincerely,
Super_Hippo Super_Hippo

2016/1/11

#
The constructor is executed when the object is created, so before it is added to the world. That's why 'getWorld' returns 'null' and you can't call methods on 'null' ('addPicture' method). You can use the 'addedToWorld' method instead of the constructor which is executed once right after the object is added to the world:
1
2
3
4
5
protected void addedToWorld(World w)
{
    game = (Game) w;
    addPicture();
}
TestUser2001 TestUser2001

2016/1/11

#
Thank you! It works perfectly.
You need to login to post a reply.