Java - 双缓冲NullPointerException

标签 java swing jframe graphics2d

我正在编写一个简单的游戏。我有 3 个类,第一个类:球,它负责处理与之相关的所有事情,第二个类是由一系列“球”组成的游戏,最后一个类是 Windows,它包含主线程。

window.paint调用game.draw来接收游戏场景的图形。而游戏本身对其进行双缓冲,以便Image对象可以移动到玩家的球位置(尚未实现)。

所以我的问题是因为我正在创建一个 Image 对象但不知何故它初始化为 null,因此我得到 NullPointerException。

以下是处理绘画的方法的来源:

public class MyWindow extends JFrame {
        //...the other code
        public void paint(Graphics g){
            thegame.draw();
            repaint();
        }
}

public class Game extends JFrame implements Runnable {
    ball[] cellmap;

    //...the other code

    public void draw(){
        Image GameImage = createImage(800,800);
        Graphics GameGraphics = GameImage.getGraphics();

        for(int i = 0;i<cellmap.length;i++)
            cellmap[i].draw(GameGraphics);

        g.drawImage(GameImage, 0, 0, this); 
    }
}

public class Ball extends JFrame {
        //...the other code
    public void draw(Graphics g){
        g.setColor(Color.red);
        g.fillOval((int)(this.x+this.radious),(int)(this.y+this.radious),
                       (int)this.radious,(int)this.radious);        
    }
}

最佳答案

1) 请阅读Java Naming Conventions

2) 直接绘制到 JFrame 不是好主意,把你的画放到JComponent , JLabel , JPanel

3) 为 PaintingSwing使用方法paintComponent ,请不要方法paint(Graphics g)draw(Graphics g)

4) 如果你想延迟或动画你的绘画使用 javax.swing.Timer

关于Java - 双缓冲NullPointerException,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9164100/

相关文章:

Java 按字符串值查找枚举

java - JTextPane : How do you update it after adding it to a layout?

java - 从外部类切换 Java 中的 jPanel

java - JPanel 面向对象图形

java - 更改 TextSize 后 TextView 不会调整大小

java - 如何组合 int 和 string 数组?

java - 如何使用Gson解析没有keyName的JSON数组?

java - 在 GRAL 中绘制多个图形

java - java Swing 中的锚定和停靠控件

Java:设计除主框架之外的 JFrame