java开发实战1200例(II)-------------074桌面弹球

package Test;

import java.awt.Color;
import java.awt.Container;
import java.awt.Dimension;
import java.awt.Graphics;
import java.awt.Point;

import javax.swing.JLabel;
import javax.swing.JPanel;

public class BallPanel extends JLabel implements Runnable {
    private int r=10;
    private int width=r*2;
    private int height=r*2;
    private Color ballColor=Color.BLUE;
    public BallPanel(){
        setPreferredSize(new Dimension(width,height));
        new Thread(this).start();
    }
    public void paintComponent(Graphics g){
        super.paintComponent(g);
        g.setColor(ballColor);
        g.fillOval(0,0,width,height);
        
    }
    public void run(){
        Container parent=getParent();
        Point myPoint=getLocation();
        while(true){
            if(parent==null){
                try {
                    Thread.sleep(50);
                } catch (InterruptedException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                }
                myPoint=getLocation();
                parent=getParent();
            }else{
                break;
            }
        }
        int sx=myPoint.x;
        int sy=myPoint.y;
        int step=(int)(Math.random()*10)%3+1;
        int dx=(Math.random()*100)>50?step:-step;
        step=(int)(Math.random()*10)%3+1;
        int dy=(Math.random()*100)>50?step:-step;
        int stime = (int) (Math.random() * 80 + 10);
        while(parent.isVisible()){
            int parentWidth=parent.getWidth();
            int parentHeight=parent.getHeight();
            setLocation(sx,sy);
            try {
                Thread.sleep(stime);
            } catch (InterruptedException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
            sx=sx+dx*5;
            sy=sy+dy*5;
            if(sy>parent.getHeight()||sy<0)
                dy=-dy;
            if(sx>parent.getWidth()||sx<0)
                dx=-dx;
        }
        
    }
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值