我正在创建一个突破游戏,我正在尝试构建一个砖层,它逐层显示砖块的图像。但我的代码编译但没有任何显示。
这是我到目前为止所做的。
主类:
public class Breakout extends Applet implements Runnable{
Thread thread = new Thread(this);
boolean running = true;
Brick b;
Image dbImage;
Graphics dbg;
public void init(){
setSize(800,600);
b = new Brick();
}
public void start(){
thread.start();
}
public void destroy(){
running = false;
}
public void stop(){
running = false;
}
public void run(){
while(running){
b.update(this);
repaint();
try{
thread.sleep(20);
}
catch (InterruptedException e){
System.out.println("AN ERROR HAS OCCURED");
}
}
}
public void update(Graphics g){
dbImage = createImage(getWidth(),getHeight());
dbg = dbImage.getGraphics();
paint(dbg);
g.drawImage(dbImage,0,0,this);
}
public void paint(Graphics g){
b.paint(g,this);
}
}
这是砖类:
public class Brick {
private URL url;
private Image brick;
Image [][] bricks = new Image[50][3];
public void brick (Breakout bR){
url = bR.getDocumentBase();
brick = bR.getImage(url,"brick.png");
for(int i =0; i < bricks.length; i++)
for(int j = 0; j < bricks[0].length; j++)
bricks[i][j] = brick;
}
public void update(Breakout bR){
}
public void paint(Graphics g, Breakout bR){
int imageWidth = bricks[0][0].getWidth(bR);
int imageHeight = bricks[0][0].getHeight(bR);
for (int i = 0; i < bricks.length; i++)
for ( int j =0; j < bricks[0].length; j++)
g.drawImage(bricks[i][j], i * imageWidth + 5, j * imageHeight + 5, bR);
}
}
感谢您的帮助。
答案 0 :(得分:1)
问题在于:
b = new Brick();
您正在调用创建一个对象,但该构造函数不存在,因此它被认为是基本的默认对象。
,而你有
public void brick (Breakout bR){
这是一些方法。不是构造函数
更改为
public Brick (Breakout bR){
和
b=new Brick(this);
答案 1 :(得分:0)
看起来你的图形区域比你想象的要小。
让我们添加一些基本的调试代码来查明问题:
public void update(Graphics g){
dbImage = createImage(getWidth(),getHeight());
//New line:
System.out.println("dbImage widthxheight = "+dbImage.getWidth()+"x"+dbImage.getHeight());
dbg = dbImage.getGraphics();
paint(dbg);
g.drawImage(dbImage,0,0,this);
}
和
public void paint(Graphics g, Breakout bR){
//New line:
Rectangle bounds = ((Graphics2D)g).getDeviceConfiguration().getBounds();
//New line:
System.out.println("bounds widthxheight = "+bounds.getWidth()+"x"+bounds.getHeight());
int imageWidth = bricks[0][0].getWidth(bR);
int imageHeight = bricks[0][0].getHeight(bR);
//New line:
System.out.println("imageSize widthxheight = "+imageWidth +"x"+imageHeight);
for (int i = 0; i < bricks.length; i++)
for ( int j =0; j < bricks[0].length; j++)
g.drawImage(bricks[i][j], i * imageWidth + 5, j * imageHeight + 5, bR);
}
根据控制台,你的图形区域有多大?
编辑:如果您根本看不到任何消息,则表示您的代码未被调用,您可能需要修改启动小程序的方式。
答案 2 :(得分:-1)
你在Breakout.java中没有主要方法。项目中至少有一个类需要一个main方法来执行它。您还需要调用Thread.start()以使run方法在Thread上执行。以this为例。