[java]代码库
package s1214键盘监听事件移动方块;
//w,a,s,d控制移动
import java.awt.Graphics;
import java.awt.event.KeyAdapter;
import java.awt.event.KeyEvent;
import javax.swing.JFrame;
import javax.swing.JPanel;
import 工具类.ThreadSleep;
public class Main1214 extends JFrame
{
static int x=50;
static int y=50;
static int speed=10;
static boolean upFlag=false;
static boolean downFlag=false;
static boolean leftFlag=false;
static boolean rightFlag=false;
public static void main(String[] args)
{
Main1214 a= new Main1214();
while(true)
{
ThreadSleep.threadSleep(30);
if(upFlag) {y-=speed;}//向上移动
if(downFlag) {y+=speed;}//向下移动
if(leftFlag) {x-=speed;}//向左移动
if(rightFlag) {x+=speed;}//向右移动
a.repaint();//重绘
}
}
Main1214()
{
this.setTitle("移动滑块"); //设置窗体标题
this.setDefaultCloseOperation(3);//设置窗体关闭方式
this.setSize(700,700); //设置窗体大小
this.setResizable(true); //设置窗体大笑可变
this.setLocationRelativeTo(null);//设置窗体居中
JPanel drawPanel=new JPanel() //创建画板对象,用来画图
{
public void paint(Graphics g)
{
super.paint(g);
g.fillRect(x,y,30,30); //画出方块
}
};
this.addKeyListener(new KeyAdapter() //匿名对象和匿名内部类的使用
{
//关键代码**************************************************************************
public void keyPressed(KeyEvent e) //按下按键
{
if(e.getKeyCode()==KeyEvent.VK_W){upFlag=true;}
if(e.getKeyCode()==KeyEvent.VK_S){downFlag=true;}
if(e.getKeyCode()==KeyEvent.VK_A){leftFlag=true;}
if(e.getKeyCode()==KeyEvent.VK_D){rightFlag=true;}
}
public void keyReleased(KeyEvent e)//松开按键
{
if(e.getKeyCode()==KeyEvent.VK_W){upFlag=false;}
if(e.getKeyCode()==KeyEvent.VK_S){downFlag=false;}
if(e.getKeyCode()==KeyEvent.VK_A){leftFlag=false;}
if(e.getKeyCode()==KeyEvent.VK_D){rightFlag=false;}
}
//关键代码**************************************************************************
});
this.add(drawPanel); //将画板添加到窗体
this.setVisible(true); //设置窗体可见
}
}