I have a Java program that is basically a game. He has a class called "World . " The class "World" has a method of 'levelChanger ()' , and the other method is makeColorArray () ' .
public class World { private BufferedImage map, map1, map2, map3; private Color[][] colorArray; public World(int scrWd, int scrHi) { try { map1 = ImageIO.read(new File("map1.png")); map2 = ImageIO.read(new File("map2.png")); map3 = ImageIO.read(new File("map3.png")); } catch (IOException e) { e.printStackTrace(); } map = map1; makeColorArray(); } private void makeColorArray() { colorArray = new Color[mapHi][mapWd];
The makeColorArray () method creates a 2d array of type Color . This array stores Color objects from a PNG image. This array is used by the paint () JPanel method to paint the world on the screen.
The levelChanger () method is used to change the levels (stages) of a game when a particular encoding is true. This is the method that calls the makeColorArray () method to recreate the color array when the game level changes.
The problem is that I have a game loop that runs in a stream. Now the picture of the swing components, such as JPanel, is executed on a different java background thread. When the game level changes, the color array object is re-executed. Now, as I said, the color-array object is used by the paint () method to paint the world on the screen. Sometimes the color grid object is still used by the background stream (unfinished painting), when, according to the logic of the game, the object is the color array is re-created, and its members are set to zero. This throws a null pointer exception , only occasionally. Obviously a race condition.
I want to know how I can stop my game stream from resetting the color array until the background rock has finished drawing.
source share