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

2012/2/26

Making the classic "Game Over" screen...

1
2
Duta Duta

2012/2/28

#
Just quickly (you've probably worked this out) but moving the call to updateImage() from the constructor to a method named public void addedToWorld(World w) should fix the problem.
danbhome danbhome

2012/4/26

#
it says that it cannot find package greenfoot after i capitalize stuff and everything
Duta Duta

2012/4/26

#
Check your import statements: Make sure you have "import greenfoot.*;". Also greenfoot must be lower-case.
danbhome danbhome

2012/5/5

#
says cant find variable getHeight
danpost danpost

2012/5/5

#
'getHeight' is probably a method and needs to be 'getHeight()'.
LittleJacob LittleJacob

2013/3/22

#
Hi, i still don't understand how to fix the NullPointerException. If someone could give me the right piece of code i would be very pleased. import greenfoot.*; // (World, Actor, GreenfootImage, Greenfoot and MouseInfo) import java.awt.Color; public class GameOver extends Actor { String msgTxt = "GAME OVER"; public GameOver() { updateImage(); } public GameOver(String txt) { msgTxt = txt; updateImage(); } private void updateImage() { GreenfootImage image = new GreenfootImage(getWorld().getWidth(), getWorld().getHeight()); // or whatever size you want the object image.setColor(Color.cyan); // color of your choice image.fill(); GreenfootImage txtImg = new GreenfootImage(msgTxt, 36, Color.black, new Color(0, 0, 0, 0)); // colors and font size of your choice image.drawImage(txtImg, (image.getWidth() - txtImg.getWidth()) / 2, (image.getHeight() - txtImg.getHeight() / 2)); // whatever else you might want to do for the image setImage(image); } }
danpost danpost

2013/3/22

#
The problem is that you are calling 'updateImage', which uses 'getWorld', from the constructor. The object is not yet in a world when being constructed, hence your NullPointerException ('getWorld' returns 'null'). To avoid this, you can update the image from the 'addedToWorld' method which is automatically called when the object is placed in a world.
import greenfoot.*;
import java.awt.Color;

public class GameOver extends Actor
{
    String msgTxt = "GAME OVER";

    public GameOver()
    {
    }

    public GameOver(String txt)
    {
        msgTxt = txt;
    }

    public void addedToWorld(World world)
    {
       GreenfootImage image = new GreenfootImage(world.getWidth(), world.getHeight());
        image.setColor(Color.cyan);
        image.fill();
        GreenfootImage txtImg = new GreenfootImage(msgTxt, 36, Color.black, new Color(0, 0, 0, 0));
        image.drawImage(txtImg, (image.getWidth() - txtImg.getWidth()) / 2, (image.getHeight() - txtImg.getHeight() / 2));
        setImage(image);
    }
}
LittleJacob LittleJacob

2013/3/23

#
Thank you very much
You need to login to post a reply.
1
2