getGraphics()上的空指针异常

时间:2013-08-11 12:19:25

标签: java swing nullpointerexception draw bufferedimage

我的应用程序看起来像那样,我在draw()方法中得到一个空指针异常,确切地说是g.drawImage(img,0,0,null)

package com.ochs.game;

import java.awt.Dimension;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.image.BufferedImage;

import javax.swing.JFrame;
import javax.swing.JPanel;

public class Game extends JPanel implements Runnable{
private static final long serialVersionUID = 8229934361462702491L;

public static final int WIDTH = 320;
public static final int HEIGHT = 240;
public static final int SCALE = 2;

public boolean isRunning;

private BufferedImage img;
private Graphics2D g2d;

public Game() {
    setFocusable(true);
    requestFocus();
    start();
}

public void start() {
    isRunning = true;
    new Thread(this).start();
}

public void stop() {
    isRunning = false;
}

public void run() {
    long start;
    init();
    while(isRunning) {
        start = System.currentTimeMillis();

        update();
        render();
        draw();

        try {
            Thread.sleep(5 - (System.currentTimeMillis() - start));
        } catch (Exception e) {
        }
    }
}

public void init() {
    img = new BufferedImage(WIDTH*SCALE, HEIGHT*SCALE, BufferedImage.TYPE_INT_RGB);
    g2d = (Graphics2D) img.getGraphics();
}

public void update() {

}

public void render() {

}

public void draw() {
    Graphics g = getGraphics();
    g.drawImage(img, 0, 0, null);    // <<<<< getting null pointer here!
}

public static void main(String[] args) {
    Dimension size = new Dimension(WIDTH*SCALE, HEIGHT*SCALE);
    Game gameComponent = new Game();
    JFrame frame = new JFrame();
    frame.setVisible(true);
    frame.setSize(size);
    frame.setLocationRelativeTo(null);
    frame.setResizable(false);
    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    frame.add(gameComponent);
}
}

现在我的问题是:为什么在尝试绘制名为img的bufferedimage时会出现空指针异常?我也尝试使用drawString()输出一些字符串,但这也给我自己一个nullpointerexception。 有没有人有建议?

4 个答案:

答案 0 :(得分:5)

您可能在渲染JPanel之前尝试通过getGraphics()获取Graphics上下文,因此该方法返回null。不要这样做。在组件上使用getGraphics()来获取Graphics上下文存在问题,其中一个是您在上面看到的问题,另一个是获得的Graphics上下文不会持久存在。有时候这是必要的,但通常我们会通过paintComponent(...)进行被动绘图。通常,Swing Timer可用于动画循环。

答案 1 :(得分:3)

我认为这是因为你试图使用getGraphics()而不是传统的paintComponent覆盖来绘制。你想使用这样的东西:drawImage is not drawing(参见最佳答案)。

答案 2 :(得分:0)

如果在该语句之前不呈现Component,那么

getGraphics()方法将返回null,因此您将获得NullPointerException,如果它被渲染,则Graphics将不稳定并且更好地使用paintComponents ......

请参阅link

也是一个例子"Better approach than getGraphics()"

答案 3 :(得分:0)

必须首先看到组件 在Game / panel

中启动线程之前尝试这个

frame.add(面板) frame.setVisible(真)

然后在Game / panel

中启动线程