我做了JAVA程序程序简单屏幕上显示矩形块用键盘上左右方向键控制左右动我觉得做没问题运行时按都动哪位大侠能帮忙找下错误啊(程序包括两类矩形块类还有主类)
import java.awt.*;
import java.awt.event.*;
public class board {
int x,y,w,h,v;
public board(int x1,int y1, int w1,int h1,int v1 ){
x=x1;y=y1;w=w1;h=h1;v=v1;}
public void draw(Graphics g){ g.setColor(Color.blue); g.fillRect(x,y,w,h); }
public void collide(dong game){
if( x < 0 || x + w> game.appW ){ v= -v; }
}
public void keyPressed(int key){
if(key == KeyEvent.VK_RIGHT){
x=x+v;
}else if(key == KeyEvent.VK_LEFT){
x=x-v;
}
}
}
主类:
import java.awt.*;
import java.applet.*;
import java.awt.event.*;
public class dong extends Applet implements KeyListener{
board board1;
int appW, appH;
public void init(){
addKeyListener(this);
appW = getWidth(); appH = getHeight();
board1 = new board( appW/2-30, appH-60, 30, 30, 20 );
}
public void paint(Graphics g){
board1.draw(g);
}
public void keyTyped(KeyEvent e){}
public void keyPressed(KeyEvent e){
int key = e.getKeyCode();
board1.keyPressed(key);
board1.collide(this);
repaint();
}
public void keyReleased(KeyEvent e){}
} |
|