Java - 双缓冲NullPointerException
我正在写一个简单的游戏。我有 3 个类,第一个是球,它负责处理与之相关的所有事情,第二个是由一系列“球”组成的游戏,最后一个是窗口,其中包含主线程。
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);
}
}
I'm writing a simple game. I have 3 classes the first one: ball which take care of every thing refereed to it, the second one game which made out of an array of "ball"s and the final one is windows, the one which contains the MAIN thread.
window.paint calls game.draw in order to receive the graphics of the game scene.While the game itself double buffering it in order that the Image object can be moved to the Player's ball location(yet to be implemented).
So my problem caused because I'm creating an Image object but somewhy this initialized to null, thus I get NullPointerException.
Here is the source of the methods which handle the painting:
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);
}
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
1) 请阅读 Java 命名约定
2) 直接绘制不是个好主意
JFrame
,将您的绘画放入JComponent
、JLabel
、JPanel
3) for 在 Swing 使用方法
paintComponent
,请不要使用方法paint(Graphics g)
或绘制(图形g)
4) 如果你想延迟或动画你的绘画使用 javax.swing.Timer
1) please read Java Naming Conventions
2) not good idea paint directly to the
JFrame
, put your painting to theJComponent
,JLabel
,JPanel
3) for Painting in Swing use method
paintComponent
, please not methodspaint(Graphics g)
ordraw(Graphics g)
4) if you want to delay or animate you painting use javax.swing.Timer