packagezhf;importjava.applet.*;importjava.awt.*;importjava.awt.event.*;publicclassKeyControlDrawextendsAppletimplementsKeyListener{privateRectangler;privateColorbackColor...
package zhf;
import java.applet.*;
import java.awt.*;
import java.awt.event.*;
public class KeyControlDraw extends Applet implements KeyListener{
private Rectangle r;
private Color backColor;
public void init(){
r=new Rectangle(0,0,40,20);
backColor=Color.WHITE;
addKeyListener(this);
}
public void paint(Graphics g){
setBackground(backColor);
g.fillRect(r.x,r.y, r.width, r.height);
}
public void keyPressed(KeyEvent e) {
int KeyCode=e.getKeyCode();
if(KeyCode==KeyEvent.VK_LEFT){
r.x-=5;
if(r.x<0)r.x=0;
repaint();
}
else if(KeyCode==KeyEvent.VK_RIGHT){
r.x+=5;
if(r.x>getSize().width-r.width)r.x=getSize().width-r.width;
repaint();
}
else if(KeyCode==KeyEvent.VK_UP){
r.y-=5;
if(r.y<0)r.y=0;
repaint();
}
else if(KeyCode==KeyEvent.VK_DOWN){
r.y+=5;
if(r.y>getSize().height-r.height)r.y=getSize().height-r.height;
repaint();
}}
public void keyReleased(KeyEvent e) {
;
}
public void keyTyped(KeyEvent e) {
char KeyChar=e.getKeyChar();
switch(KeyChar){
case 'r':{
backColor=Color.RED;
repaint();
break;
}
case 'g':{
backColor=Color.green;
repaint();
break;
}
case 'b':{
backColor=Color.BLUE;
repaint();
break;
}
case 'w':{
backColor=Color.WHITE;
repaint();
break;
}}}}
展开