Question

I have tried to paint the background to the window via the paint method and it seems I have succeeded.But I found a problem on the console.That's "NullPointerException".

The GameWindow Code:

package com.vboar.game;

import java.awt.Graphics;
import java.awt.Toolkit;
import java.awt.image.BufferedImage;
import java.util.ArrayList;
import java.util.List;
import javax.swing.JFrame;

public class GameWindow extends JFrame {

private List<BackGround> allBg = new ArrayList<BackGround>();
private BackGround nowBg = null;

public GameWindow() {
    this.setTitle("IGame Beta v1.0");
    this.setSize(1000, 600);
    int width = Toolkit.getDefaultToolkit().getScreenSize().width;
    int height = Toolkit.getDefaultToolkit().getScreenSize().height;
    this.setLocation((width - 1000)/2, (height - 600)/2);
    this.setVisible(true);
        StaticValue.init();
    for (int i = 1; i <= 10; i++) {
        this.allBg.add(new BackGround(i));
    }
    this.nowBg = this.allBg.get(0);
    this.repaint();
    this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    this.setResizable(false);
}

public static void main(String[] args) {
    new GameWindow();
}

@Override
public void paint(Graphics g) {
    BufferedImage image = new   BufferedImage(1000,600,BufferedImage.TYPE_3BYTE_BGR);
    Graphics g2 = image.getGraphics();
    g2.drawImage(this.nowBg.getBgImage(), 0, 0, this);
    g.drawImage(image, 0, 0, this);
}
}


The BackGround Code:

package com.vboar.game;

import java.awt.image.BufferedImage;
import java.util.ArrayList;
import java.util.List;

public class BackGround {
private BufferedImage bgImage = null;
private int sort;
public BufferedImage getBgImage() {
    return bgImage;
}
public BackGround(int sort) {
    this.sort = sort;
    bgImage = StaticValue.allbgImage.get(0);
}
}

The StaticValue Code:

package com.vboar.game;

import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

import javax.imageio.ImageIO;

public class StaticValue {
public static BufferedImage blockImage = null;
public static BufferedImage treeImage = null;
public static BufferedImage startImage = null;
public static BufferedImage deadImage = null;
public static List<BufferedImage> allbgImage = new ArrayList<BufferedImage>();
public static List<BufferedImage> alliImage = new ArrayList<BufferedImage>();
public static String imagePath = System.getProperty("user.dir") + "/bin/";

public static void init() {
    try {
        blockImage = ImageIO.read(new File(imagePath + "block.png"));
        treeImage = ImageIO.read(new File(imagePath + "greentree.png"));
        startImage = ImageIO.read(new File(imagePath + "startbg.png"));
        deadImage = ImageIO.read(new File(imagePath + "9.png"));
    } catch (IOException e) {
        e.printStackTrace();
    }
    for (int i = 1; i <= 8; i++) {
        try {
            alliImage.add(ImageIO.read(new File(imagePath  + i + ".png")));
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
    for (int i = 1; i <= 10; i++) {
        try {
            allbgImage.add(ImageIO.read(new File(imagePath  + "background" + i + ".png")));
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}
}

The full exception stackTrace:

Exception in thread "AWT-EventQueue-0" java.lang.NullPointerException {
at com.vboar.game.GameWindow.paint(GameWindow.java:41)
at javax.swing.RepaintManager$3.run(Unknown Source)
at javax.swing.RepaintManager$3.run(Unknown Source)
at java.security.AccessController.doPrivileged(Native Method)
at java.security.ProtectionDomain$1.doIntersectionPrivilege(Unknown Source)
at javax.swing.RepaintManager.paintDirtyRegions(Unknown Source)
at javax.swing.RepaintManager.paintDirtyRegions(Unknown Source)
at javax.swing.RepaintManager.prePaintDirtyRegions(Unknown Source)
at javax.swing.RepaintManager.access$1000(Unknown Source)
at javax.swing.RepaintManager$ProcessingRunnable.run(Unknown Source)
at java.awt.event.InvocationEvent.dispatch(Unknown Source)
at java.awt.EventQueue.dispatchEventImpl(Unknown Source)
at java.awt.EventQueue.access$200(Unknown Source)
at java.awt.EventQueue$3.run(Unknown Source)
at java.awt.EventQueue$3.run(Unknown Source)
at java.security.AccessController.doPrivileged(Native Method)
at java.security.ProtectionDomain$1.doIntersectionPrivilege(Unknown Source)
at java.awt.EventQueue.dispatchEvent(Unknown Source)
at java.awt.EventDispatchThread.pumpOneEventForFilters(Unknown Source)
at java.awt.EventDispatchThread.pumpEventsForFilter(Unknown Source)
at java.awt.EventDispatchThread.pumpEventsForHierarchy(Unknown Source)
at java.awt.EventDispatchThread.pumpEvents(Unknown Source)
at java.awt.EventDispatchThread.pumpEvents(Unknown Source)
at java.awt.EventDispatchThread.run(Unknown Source)
}

It's my first time to ask on the stackoverflow.com so that the codes may be very ugly. Also, I'm not an English speaker and I have made terrible writing. Could you please help me,a Java learner,to solve this problem?

Thank you in advance.

Vboar

Was it helpful?

Solution

After doing some tests it seems that the error you are getting is caused because the image you are trying to draw has not been loaded by the first time you try to draw the image on the window.

The error handling within the swing components will handle the error for you though you should put a try catch statement around where you draw the image to catch this error yourself, like so:

try {
    g2.drawImage(this.nowBg.getBgImage(), x, 0, this);
} catch (Exception e) {
    e.printStackTrace(); //optional for seeing the error message
}

After looking at you code there are a few other recommendations that I came up with that can help your current program and your programming skills overall.

  1. Don't have variables that are both public and static unless its going to be final or readonly. It's a general programming rule that applies to multiple languages and generally makes it tougher to implement and maintain a more complex program.

  2. When you are creating the background classes within your GameWindow class you are essentially duplicating the images that were loaded in the StaticValue class. This essentially makes the loading time longer and increases memory usage for no gain. Try loading and using the images within only a single class rather than multiple.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top