import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import com.bruceeckel.swing.*;
class BasicModel{
int x,y,width=26,height=26;
BasicModel(int x,int y){
this.x=x;
this.y=y;
}
}
class Model1 extends JPanel implements Runnable{
private BasicModel[] m1={new BasicModel(100,100),new BasicModel(100,126),new BasicModel(100,152),new BasicModel(100,178),};
private int i;
private long eventtime=0,delaytime=1000;
public void paintComponent(Graphics g){
super.paintComponent(g);
for(i=0;i<m1.length;i++){
g.setColor(Color.BLACK);
g.drawRect(m1[i].x,m1[i].y,m1[i].width-1,m1[i].height-1);
g.setColor(Color.RED);
g.fillRect(m1[i].x,m1[i].y,m1[i].width-2,m1[i].height-2);
}
}
public void goRight(){
for(i=0;i<m1.length;i++)
m1[i].x+=26;
repaint();
}
public void goLeft(){
for(i=0;i<m1.length;i++)
m1[i].x-=26;
repaint();
}
public void run(){
while(m1[3].y<400){
if(System.currentTimeMillis()>=eventtime){
for(i=0;i<m1.length;i++)
m1[i].y+=26;
repaint();
eventtime=System.currentTimeMillis()+delaytime;
}
}
}
}
public class DrawModels2 extends JFrame{
private static Model1 m=new Model1();
class KListener extends KeyAdapter{
public void KeyPressed(KeyEvent e){
switch(e.getKeyCode())
{ case KeyEvent.VK_RIGHT : m.goRight();break;
case KeyEvent.VK_LEFT : m.goLeft();break;
}
}
}
KListener kl=new KListener();
public DrawModels2(){
Container cp=getContentPane();
m.addKeyListener(kl);
cp.add(m);
}
public static void main(String[] args){
DrawModels2 a=new DrawModels2();
Thread b=new Thread(a.m);
Console.run(a,500,500);
b.start();
}
}
这个程序的目的是产生一个矩形,然后一边下落,一边可以受键盘操作向左向右移动,其他的效果都还好,就是不能受键盘操作,请各位帮忙看看,谢谢!!
main方法里的Console.run(a,500,500)是为了让程序结果显示出来写的一个小小的工具类里的方法,跟其他没什么联系.