📄 playoneball.java
字号:
package applet;
import java.awt.Color;
import java.awt.Graphics; //画笔
import java.applet.Applet; //经编译后可嵌入HTML文件
import java.applet.AudioClip;
import java.awt.*;
import java.awt.event.*;
public class PlayOneBall extends Applet implements Runnable, ActionListener{
private Thread timer;
int BallDiameter; //定义小球直径
int StepLength; //定义移动步长
float x, y; //定义小球坐标
double angle; //定义小球运动方向角,以水平向右为初始方向
boolean started=false;
AudioClip sound;
Button btnStart=new Button("开始");
Button btnStop=new Button("停止");
Button btnExit=new Button("退出");
public void init(){
this.setSize(500,500);
this.add(btnStart);
this.add(btnStop);
this.add(btnExit);
btnStart.addActionListener(this);
btnStop.addActionListener(this);
btnExit.addActionListener(this);
sound=this.getAudioClip(this.getCodeBase(),"applet/ding.wav");
}
public void update(Graphics g){
paint(g);
}
public void paint(Graphics g){
g.setColor(Color.YELLOW);
g.fillRect(0, 0, this.getWidth(),this.getHeight());
g.setColor(Color.RED);
g.fillArc(Math.round(x), Math.round(y), BallDiameter, BallDiameter, 0, 360);
}
public void start() {
timer = new Thread(this);
timer.start();
x=(float) (Math.random()*this.getWidth()*0.8); //定义小球初始横坐标
y=(float) (Math.random()*this.getHeight()*0.8); //定义小球初始纵坐标
angle=Math.random()*Math.PI*2; //定义小球运动初始角
BallDiameter=(int) (Math.random()*50+30); //定义小球的直径
StepLength=(int) (Math.random()*10+5); //定义小球的移动步长
}
public void run() {
while (timer == Thread.currentThread() && started) {
try {
timer.sleep(50);
} catch (InterruptedException e) {
}
//小球运动方向和坐标的变化
if(x<StepLength || x>this.getWidth()-BallDiameter){
sound.play();
angle=Math.PI-angle;
}
if(y<StepLength || y>this.getHeight()-BallDiameter){
sound.play();
angle=2*Math.PI-angle;
}
x=(float) (x+StepLength*Math.cos(angle));
y=(float) (y-StepLength*Math.sin(angle));
repaint(); //重绘
}
}
public void actionPerformed(ActionEvent e) {
if(e.getSource()==btnStart){
started=true;
sound.play();
start();
}else if(e.getSource()==btnStop){
started=false;
sound.stop();
stop();
}else
System.exit(0);
}
}
⌨️ 快捷键说明
复制代码
Ctrl + C
搜索代码
Ctrl + F
全屏模式
F11
切换主题
Ctrl + Shift + D
显示快捷键
?
增大字号
Ctrl + =
减小字号
Ctrl + -