from Chapter 9 in 'Introduction to Programming with Greenfoot SE : loop-practice
The program throws a NullPointerException the first time I start the program.
Any ideas?


1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 | import greenfoot.*; /** * A board to scribble on. * * @author Michael Kölling * @version 1.0 */ public class ChalkBoard extends World { // Where to write the next text: private int x; private int y; /** * Create a new chalk board. */ public ChalkBoard() { super ( 800 , 600 , 1 ); clear(); practice(); } /** * This is the method for you to practice. Add your code here. */ public void practice() { write( 7 ); // an example of writing a number // Replace this with your own code } /** * Write a number onto the board. */ public void write( int number) { write(String.valueOf(number)); } /** * Write a character onto the board. */ public void write( char character) { write(String.valueOf(character)); } /** * Write some text onto the board. */ public void write(String text) { addObject( new Text(text), x, y); x += 120 ; if (x > getWidth()- 100 ) { x = 100 ; y += 80 ; } } /** * Wipe the board. */ public void clear() { removeObjects(getObjects(Text. class )); x = 100 ; y = 100 ; } } |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 | import greenfoot.*; /** * An object showing some text. * * @author Michael Kölling * @version 1.0 */ public class Text extends Actor { public Text(String text) { GreenfootImage img = new GreenfootImage(text, 64 , Color.WHITE, null ); setImage(img); } } |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 | /** * An object showing some text. * * @author Michael Kölling * @version 1.0 */ public class Text extends Actor { public Text(String text) { GreenfootImage img = new GreenfootImage(text, 64 , Color.WHITE, Color.BLACK); //changed last parameter from null to Color.BLACK setImage(img); } } |