实现可变色小方框的移动及变色。通过键盘的方向键也可控制小方框的移动,通过字母键B,G等可更改小方框的颜色。
import java.awt.*;
import java.awt.event.*;
public class KeyBoardDemo extends Frame implements KeyListener{
static final int SQUARE_SIZE=20; //小方框的边长
Color squareColor; //小方框的颜色
int squareTop,squareLeft; //小方框的左上角坐标
public KeyBoardDemo() {
squareTop=100; //初始小方框位置
squareLeft=100;
squareColor=Color.red; //初始颜色设置为红色
addKeyListener(this); //注册键盘事件监听
repaint();
}
public void paint(Graphics g) {
g.setColor(squareColor);
g.fillRect(squareLeft, squareTop, SQUARE_SIZE,SQUARE_SIZE );
}
/*用键盘控制小方框颜色的改变*/
public void keyTyped(KeyEvent evt) {
char ch=evt.getKeyChar(); //获取输入字符
if(ch=='B'||ch=='b') {
squareColor=Color.blue;
repaint();
}else if(ch=='G'||ch=='g') {
squareColor=Color.green;
repaint();
}
}
/*用键盘控制小方框的移动*/
public void keyPressed(KeyEvent evt) {
int key=evt.getKeyCode(); //获取按键的编码
if(key==KeyEvent.VK_LEFT) { //按键为左箭头
squareLeft-=8;
if(squareLeft<3)
squareLeft=3;
repaint();
}else if(key==KeyEvent.VK_RIGHT) { //按键为右箭头
squareLeft+=8;
if(squareLeft>getWidth()-3-SQUARE_SIZE)
squareLeft=getWidth()-3-SQUARE_SIZE;
repaint();
}else if(key==KeyEvent.VK_UP) { //按键为上箭头
squareTop-=8;
if(squareTop<23)
squareTop=23;
repaint();
}else if(key==KeyEvent.VK_DOWN) { //按键为下箭头
squareTop+=8;
if(squareTop>getHeight()-3-SQUARE_SIZE)
squareTop=getHeight()-3-SQUARE_SIZE;
repaint();
}
}
public void keyReleased(KeyEvent evt) {}
public static void main(String[] args) {
// TODO Auto-generated method stub
Frame x=new KeyBoardDemo();
x.setSize(300,300);
x.setVisible(true);
}
}
运行结果: