【Java开源代码栏目提醒】:以下是网学会员为您推荐的Java开源代码-Movement.java,希望本篇文章对您学习有所帮助。
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import java.math.*;
public class Movement {
public static void main(String[] args) {
running move = new running();
move.setBounds(10, 10, 450, 450);
move.setVisible(true);
move.setTitle("模拟曲线运动");
// 添加窗口关闭事件
move.addWindowListener(new WindowAdapter(){
public void windowClosing(WindowEvent e){
System.exit(0);
}
});
}
}
class running extends JFrame implements Runnable,ActionListener{
// 控制球的线程
Thread BlueBall;
Ball blue;
// 开始按钮
JButton Start = new JButton("开始");
// 退出按钮
JButton End = new JButton("退出");
// 如果run为true则挂起线程,否则
boolean Run = false;
boolean starting = true;
double t = -1;
// 构造方法,设置界面的相关属性
running(){
BlueBall = new Thread(this);
blue = new Ball(Color.blue);
setLayout(null);
add(blue);
add(Start);
add(End);
// 蓝球的起始位置
blue.setLocation(80, 100);
// 设置此按钮的动作命令。
Start.setActionCommand("Start");
// 设置按钮的大小和位置
Start.setBounds(305, 370, 60, 40);
// 添加事件处理
Start.addActionListener(this);
End.setActionCommand("End");
End.setBounds(375, 370, 60, 40);
End.addActionListener(this);
}
public void run() {
while(true){
// 如果Run为true,挂起线程
while(Run)
Stop();
t= t + 2;
if(t>400) t = 0;
// 蓝球的坐标
int x = (int)t+80;
int y = (int)(Math.sin(t/3.1415)*100+200);
// 重新设定位置
blue.setLocation(x, y);
try {
// 休眠50毫秒
Thread.sleep(50);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
// 事件处理
public void actionPerformed(ActionEvent e) {
String cmd = e.getActionCommand();
if(cmd.equals("Start")){
Start.setText("暂停");
Start.setActionCommand("Stop");
if(starting){
BlueBall.start();
starting = false;
}
else{
// 唤醒线程
renew();
Run = false;
}
}
else if(cmd.equals("End")){
Run = false;
this.dispose();
System.exit(0);
}
else if(cmd.equals("Stop")){
Start.setText("开始");
Start.setActionCommand("Start");
Run = true;
}
}
public synchronized void renew(){
notifyAll();
}
public synchronized void Stop(){
try {
wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
class Ball extends Canvas{
Color color;
Ball(Color color){
setSize(10,10);
this.color = color;
}
public void paint(Graphics g){
g.setColor(color);
g.fillOval(0, 0, 10, 10);
}
}
上一篇:
MoveFileUtil.java
下一篇:
围手术期患者抗菌药物使用情况调查分析