Java getGraphics() 上的空指针异常

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/18171825/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-11 23:00:20  来源:igfitidea点击:

Null Pointer Exception on getGraphics()

javaswingnullpointerexceptiondrawbufferedimage

提问by user2410644

my application looks like that, i am getting a null pointer exception at the draw() method, to be exact at g.drawImage(img, 0, 0, null)

我的应用程序看起来像这样,我在 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);
}
}

Now my question is: why do i get a null pointer exception when trying to draw the bufferedimage called img? I also tried just outputting some string by using drawString() but this just gives myself a nullpointerexception, too. does anyone has an advice?

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

回答by Jlewis071

I think it's because you're trying to draw using getGraphics() instead of the conventional override of paintComponent. You want to use something like this: drawImage is not drawing(see the top answer).

我认为这是因为您试图使用 getGraphics() 而不是传统的paintComponent覆盖来绘制。你想使用这样的东西:drawImage 不是在绘图(请参阅顶部答案)。

回答by Hovercraft Full Of Eels

You're likely trying to get the Graphics context via getGraphics()before the JPanel has been rendered, and thus the method returns null. Don't do this. There are problems with using getGraphics()on a component to get the Graphics context, one of which is the problem you're seeing above, and another is that the Graphics context obtained will not persist. There are occasions when this is necessary to do, but usually we do passive drawing via paintComponent(...). Often a Swing Timer can be used for the animation loop.

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

回答by Sukhbir

getGraphics() method will return null if Component is not rendered till that statement and thus you will get NullPointerException, also if it is rendered Graphics will not be stable and better to use a paintComponents...

如果在该语句之前未呈现组件,则 getGraphics() 方法将返回 null,因此您将获得 NullPointerException,如果呈现图形将不稳定,最好使用paintComponents...

See link.

链接

Also an Example "Better approach than getGraphics()"

还有一个示例“比 getGraphics() 更好的方法”

回答by Vasilis

the Component must first be visible try this before you start the thread in Game/panel

组件必须首先可见,然后在游戏/面板中启动线程之前尝试此操作

frame.add(panel) frame.setVisible(true)

frame.add(panel) frame.setVisible(true)

then start the thread in Game/panel

然后在游戏/面板中启动线程