我正在编写一个简单的游戏。我有 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) 为 Painting在 Swing使用方法paintComponent
,请不要方法paint(Graphics g)
或draw(Graphics g)
4) 如果你想延迟或动画你的绘画使用 javax.swing.Timer
关于Java - 双缓冲NullPointerException,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9164100/