文档库 最新最全的文档下载
当前位置:文档库 › java编写弹跳的小球

java编写弹跳的小球

import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
//可以不是public 类
public class jxiaoqiu extends JFrame implements ActionListener,Runnable{
Thread thread;
JButton startButton,threadButton,stopButton;
boolean flag=true;
JPanel canvas;
static final int WIDTH=15,HEIGHT=15;//居然是WIDTH写错了
int x=0,y=0,dx=2,dy=2;

public jxiaoqiu(){
setTitle("线程对比实验,重画模式");

addWindowListener(new WindowAdapter(){
public void windowClosing(WindowEvent e){
System.exit(0);
}

});

//Container contentPane=getContentPane();//完全没有必要啊
canvas=new JPanel();
canvas.setBackground(new Color(120,220,250));
//contentPane.add(canvas,"Center");//不是BorderLayout.CENTER?
add(canvas,BorderLayout.CENTER);
//contentPane.add(can)

JPanel p=new JPanel();

startButton=new JButton("不使用线程");
startButton.addActionListener(this);
p.add(startButton);

threadButton=new JButton("使用线程");
threadButton.addActionListener(this);
p.add(threadButton);

stopButton=new JButton("停止");
stopButton.addActionListener(this);
p.add(stopButton);

//contentPane.add(p,"South");
add(p,"South");//add(p,BorderLayout.SOUTH);是正规的

setSize(300,200);
setVisible(true);


}
public void actionPerformed(ActionEvent e){
if(e.getSource()==startButton){
bounce();

}
else if(e.getSource()==threadButton){
start();
}

else {
stop();
}

}


public void move(boolean yn){
Graphics g=canvas.getGraphics();
g.setColor(canvas.getBackground());//画图的组建使用的方法:设置背景色
g.fillOval(x,y,WIDTH,HEIGHT);//擦出之前的小球,否则是画线了

Dimension d=canvas.getSize();
if(x<0){x=0;dx=-dx;}
if(y<0){y=0;dy=-dy;}
if(x+WIDTH>d.width){x=d.width-WIDTH;dx=-dx;}//去掉WIDTH,越界后不回来
if(y+HEIGHT>d.height){y=d.height-HEIGHT;dy=-dy;}

x+=dx;y+=dy;

g.setColor(Color.red);//设背景色为红色
g.fillOval(x,y,WIDTH,HEIGHT);//画小球
if(yn=true){
try{
thread.sleep(20);
}
catch(InterruptedException e){}
}
else {
double z=0.371;
for(int k=0;k<99999;k++){
z=4*z*(1-z);
}

}

}
public void start(){
flag=true;
thread=new Thread(this);
thread.start();
}

public void run(){
while(flag){
move(true);
}
}


public void stop(){
flag=false;
}


public void bounce(){
int i=0;
while(flag &&i<1000){
move(flag);
i++;
}
}

public static void main(String args[]){
new jxiaoqiu();
}

}

相关文档
相关文档 最新文档