我对java编程很新,只是遵循关于用Java编写小游戏的指南。所以我必须使用Graphics类中的drawImage方法绘制一个Image。我已经覆盖了paint方法,并尝试调用g.drawImage(myImage / 类图像实例 /,character.getX,character.get,this)。现在Eclipse说我需要一个ImageObserver,我认为是正确的,但我想当我覆盖该方法并将Argument作为图形实例(此处命名为g)类时,这是g的引用,这是我的ImageObserver。
package Game;
import java.applet.Applet;
import java.awt.Color;
import java.awt.event.KeyEvent;
import java.awt.event.KeyListener;
import java.awt.image.ImageObserver;
import java.awt.Frame;
import java.net.URL;
import java.awt.Graphics;
import java.awt.Image;
import java.awt.image.ImageObserver;
public class MainGame extends Applet implements Runnable, KeyListener {
public final static int width = 800;
public final static int height = 400;
private Bird bird;
private Image image,character;
private URL base;
private Graphics second;
public static int getwidth() {
return width;
}
public static int getheight() {
return height;
}
@Override
public void init() {
// TODO Auto-generated method stub
super.init();
setSize(width, height);
setBackground(Color.BLACK);
setFocusable(true);
addKeyListener(this);
Frame frame = (Frame) this.getParent().getParent();
frame.setTitle("MyApplet");
try {
base = getDocumentBase();
} catch (Exception e) {
// TODO: handle exception
}
//Path of your Image
character = getImage(base, "path to .png image (removed)");
}
@Override
public void start() {
// TODO Auto-generated method stub
super.start();
Thread thread = new Thread(this);
thread.start();
}
@Override
public void keyTyped(KeyEvent e) {
// TODO Auto-generated method stub
}
@Override
public void keyPressed(KeyEvent e) {
// TODO Auto-generated method stub
switch(e.getKeyCode()) {
case KeyEvent.VK_UP:
bird.resetSpeed();
break;
case KeyEvent.VK_KP_DOWN:
System.out.println("Do nothing");
break;
case KeyEvent.VK_SPACE:
bird.resetSpeed();
break;
}
}
@Override
public void keyReleased(KeyEvent e) {
// TODO Auto-generated method stub
}
@Override
public void run() {
// TODO Auto-generated method stub
while(true) {
repaint();
bird.update();
try{Thread.sleep(17);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
@Override
public void update(Graphics g) {
// TODO Auto-generated method stub
super.update(g);
if (image == null) {
image = createImage(this.getWidth(), this.getHeight());
second = image.getGraphics();
}
second.setColor(getBackground());
second.fillRect(0, 0, getWidth(), getHeight());
second.setColor(getForeground());
paint(second);
g.drawImage(image, 0, 0, this);
}
@Override
public void paint(Graphics g) {
// TODO Auto-generated method stub
g.drawImage(character, bird.getCenterX(), bird.getCenterY(), null );
}
public static void main(String[] args) {
// TODO Auto-generated method stub
}
}