package Test;
import java.awt.Color;
import java.awt.EventQueue;
import java.awt.Graphics;
import javax.swing.JFrame;
import javax.swing.JPanel;
public class BilliardBallFrame extends JFrame {
public static void main(String[] args){
EventQueue.invokeLater(new Runnable(){
public void run(){
BilliardBallFrame frame=new BilliardBallFrame();
frame.setVisible(true);
}
});
}
public BilliardBallFrame(){
super();
setBounds(100,100,326,202);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setTitle("撞球动画");
BilliardBallPanel panel=new BilliardBallPanel();
getContentPane().add(panel);
Thread thread=new Thread(panel);
thread.start();
}
class BilliardBallPanel extends JPanel implements Runnable{
int x1=0;
int y1=60;
int width=30;
int height=30;
int x2=326-30;
int y2=60;
public void paint(Graphics g){
//绘制两个小球
g.clearRect(0, 0, getWidth(), getHeight());
g.setColor(Color.BLUE);
g.fillOval(x1, y1, width, height);
g.setColor(Color.RED);
g.fillOval(x2, y2, width,height);
}
public void run(){
boolean flag1=true;
boolean flag2=true;
while(true){
if(x1+width>=x2+1){
//小球撞击
x1=x1+5;
width=width-10;
x2=x1+width;
flag1=false;
flag2=false;
repaint();
}else{
//小球1从左向右移动
if(flag1){
x1=x1+10;
width=30;
}else{
//小球1从右向左移动
x1=x1-10;
width=30;
//小球1撞墙
if(x1<=0){
x1=0;
flag1=true;
}
}
if(flag2){
//小球2从向左移动
x2=x2-10;
width=30;
}else{
//相撞后从左向右移动
x2=x2+10;
width=30;
//小球2撞墙
if(x2>=getWidth()-width){
x2=getWidth()-width;
flag2=true;
}
}
}
try {
Thread.sleep(200);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
repaint();
}
}
}
}