📄 moveballbykey.java
字号:
package applet;
import java.applet.Applet;
import java.applet.AudioClip;
import java.awt.Color;
import java.awt.Graphics;
import java.awt.Image;
import java.awt.event.KeyEvent;
import java.awt.event.KeyListener;
public class MoveBallByKey extends Applet implements KeyListener{
int BallDiameter; //定义小球直径
int StepLength; //定义移动步长
int x, y; //定义小球坐标
AudioClip impactsound,music;
public void init(){
impactsound=this.getAudioClip(this.getCodeBase(),"applet/ding.wav");
music=this.getAudioClip(this.getCodeBase(),"applet/情义两心知.mid");
music.play();
music.loop();
this.addKeyListener(this);
}
public void update(Graphics g){
paint(g); //不进行背景清除
}
public void paint(Graphics g){
Image offImage=this.createImage(this.getWidth(),this.getHeight());
Graphics offGraphics=offImage.getGraphics();
offGraphics.setColor(Color.BLACK);
offGraphics.drawString("小球坐标("+(int)x+", "+(int)y+")",10,10);
//offGraphics.setColor(new Color((int)(Math.random()*256),(int)(Math.random()*256),(int)(Math.random()*256)));
offGraphics.setColor(Color.RED);
offGraphics.fillArc(x, y, BallDiameter, BallDiameter, 0, 360);
g.drawImage(offImage,0,0,this);
}
public void start() {
x=(int) (Math.random()*this.getWidth()*0.8); //定义小球初始横坐标
y=(int) (Math.random()*this.getHeight()*0.8); //定义小球初始纵坐标
BallDiameter=30; //定义小球的直径
StepLength=2; //定义小球的移动步长
}
public void keyPressed(KeyEvent e) {
switch(e.getKeyCode()){
case 37: //按左方向键
x=x-StepLength;
break;
case 38: //按上方向键
y=y-StepLength;
break;
case 39://按右方向键
x=x+StepLength;
break;
case 40://按下方向键
y=y+StepLength;
break;
}
if(x<0){ //碰左壁
x=0;
impactsound.play();
}
if(x>=this.getWidth()-BallDiameter){ //碰右壁
x=this.getWidth()-BallDiameter;
impactsound.play();
}
if(y<0){ //碰上壁
y=0;
impactsound.play();
}
if(y>=this.getHeight()-BallDiameter){ //碰下壁
y=this.getHeight()-BallDiameter;
impactsound.play();
}
repaint();
}
public void keyTyped(KeyEvent e) {
}
public void keyReleased(KeyEvent e) {
}
}
⌨️ 快捷键说明
复制代码
Ctrl + C
搜索代码
Ctrl + F
全屏模式
F11
切换主题
Ctrl + Shift + D
显示快捷键
?
增大字号
Ctrl + =
减小字号
Ctrl + -