JAVA。图形不会从draw()函数加载

时间:2017-07-19 18:57:16

标签: java applet awt

import java.awt.*;
import java.awt.event.*;
import java.applet.*;

public class snakeGame extends Applet implements Runnable, KeyListener{

private snake snk = new snake();
private Thread thread;
private Graphics gfx;
private Image img;

private boolean game = true;

public void init(){
    setBackground(Color.black);
    this.setSize(new Dimension(800,800));
    this.addKeyListener(this);
    img = createImage(800, 800);
    gfx = img.getGraphics();
    thread = new Thread();
    thread.start();
}

public void paint(Graphics g){
    //g.setColor(Color.white);
    //g.fillRect(snk.getX(), snk.getY(), 10, 10);
    snk.draw(g);
}

public void update(Graphics g){
    paint(g);
}

public void repaint(Graphics g){
    paint(g);
}

public void run(){
    while(game){

        //snk.move();
        if(snk.getDiry() == -1){
            snk.y -= 10;
        }
        if(snk.getDiry() == 1){
            snk.y += 10;
        }
        if(snk.getDirx() == -1){
            snk.x -= 10;
        }
        if(snk.getDirx() == 1){
            snk.x += 10;
        }
        repaint();

        try{
            Thread.sleep(200);
        }
        catch(InterruptedException e){
            e.printStackTrace();
        }
    }
}

public void keyPressed(KeyEvent e){
    if (e.getKeyCode() == KeyEvent.VK_UP){
        snk.setDirx(0);
        snk.setDiry(-1);
        System.out.println("UP");
    }
    else if (e.getKeyCode() == KeyEvent.VK_DOWN){
        snk.setDirx(0);
        snk.setDiry(1);
        System.out.println("DOWN");
    }
    else if (e.getKeyCode() == KeyEvent.VK_LEFT){
        snk.setDirx(-1);
        snk.setDiry(0);
        System.out.println("LEFT");
    }
    else if (e.getKeyCode() == KeyEvent.VK_RIGHT){
        snk.setDirx(1);
        snk.setDiry(0);
        System.out.println("RIGHT");
    }
    else{
        System.out.println("Wrong key pressed");
    }
}

public void keyReleased(KeyEvent e){
}

public void keyTyped(KeyEvent e){
}
}

这是snakeGame类的代码。还有另一个名为“snake.java”的文件,其中包含变量的访问器和变换器以及绘制函数的定义。这是snake.java

import java.awt.*;

public class snake {

public int x, y;
private int dirx, diry;

public snake(){
    this.x = 400;
    this.y = 400;
    this.dirx = 0;
    this.diry = 1;
}

public void draw(Graphics g){
    g.setColor(Color.white);
    g.fillRect(getX(), getY(), 20, 20);
}

public int getX(){
    return x;
}

public int getY(){
    return y;
}

public int getDirx(){
    return dirx;
}

public int getDiry(){
    return diry;
}

public void setDirx(int dirx){
    this.dirx = dirx;
}

public void setDiry(int diry){
    this.diry = diry;
} 
}

蛇不会出现在applet窗口中。请帮我看看代码中有什么问题,以及如何使代码更好。我是编码和StackOverflow的新手,所以如果我犯了一些愚蠢的错误,请原谅我。

提前致谢

和平

0 个答案:

没有答案