毕业论文开发语言企业开发JAVA技术.NET技术WEB开发Linux/Unix数据库技术Windows平台移动平台嵌入式论文范文英语论文
您现在的位置: 毕业论文 >> java技术 >> 正文

java小程序三个球碰撞变色问题

更新时间:2012-5-25:  来源:毕业论文

import java.awt.Color;
import java.awt.Frame;
import java.awt.Graphics;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;
import java.util.ArrayList;
import java.util.List;

public class Main {
    public static void main(String args[]) {
        Mywindow win = new Mywindow();
        new Ball(20, 20, win);
        new Ball(300, 20, win);
        new Ball(100, 200, win);
        win.runFrame();

    }
}

class Mywindow extends Frame {
    List<Ball> balls = new ArrayList<Ball>();

    Mywindow() {
        setBackground(Color.black);
        addWindowListener(new WindowAdapter() {
            public void windowClosing(WindowEvent e) {
                System.exit(0);
            }
        });
        setSize(350, 350);
        setVisible(true);
    }

    public void runFrame() {
        Thread t = new Thread(new MoveThread());
        t.start();
    }

    public void setBalls(List<Ball> balls) {
        this.balls = balls;
    }

    public void addBall(Ball ball) {
        this.balls.add(ball);
    }

    public void paint(Graphics g) {
        for (Ball b : balls) {
            b.draw(g);
        }
        super.paint(g);
    }

    class MoveThread implements Runnable {

        @Override
        public void run() {
            while (true) {
                repaint();
                try {
                    Thread.sleep(50);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        }
    }
}

class Ball {
    int rgb = 0;
    Color color;
    int x, y;
    int dx = 5, dy = 5;
    Mywindow win;

    Ball(int x, int y, Mywindow win) {
        this.x = x;
        this.y = y;
        this.win = win;
        win.addBall(this);
    }

    public void doColor() {
        rgb = (int) (Math.random() * 0xFFFFFF);
        color = new Color(rgb);
    }

    public void draw(Graphics g) {
        Color c = g.getColor();
        g.setColor(color);
        g.fillOval(x, y, 50, 50);
        g.setColor(c);
        move();
    }

    public void move() {
        if (x <= 0) {
            dx = 5;
            doColor();
        } else if ((x + 50) >= win.getWidth()) {
            dx = -5;
            doColor();
        }
        if (y <= 30) {
            dy = 5;
            doColor();
        } else if ((y + 50) >= win.getHeight()) {
            dy = -5;
            doColor();
        }
        x = x + dx;
        y = y + dy;
    }
}

设为首页 | 联系站长 | 友情链接 | 网站地图 |

copyright©youerw.com 优尔论文网 严禁转载
如果本毕业论文网损害了您的利益或者侵犯了您的权利,请及时联系,我们一定会及时改正。