import java.awt.Color;
import java.awt.Graphics2D;
import java.awt.Image;
import java.awt.image.BufferedImage;

import javax.swing.ImageIcon;
import javax.swing.JFrame;
import javax.swing.JLabel;


public class ColorBall extends Thread {
	
	private JLabel mainLabel;
	private final int width;
	private final int height;
	private final Graphics2D g;
	private int x; // X座標
	private int y; // Y座標
	private int xx;
	private int yy;
	private int interval;
	private Color color;
	
	public void run(){
		for(;;){
			preset(x, y);
			if ((x+xx) > width || (x+xx) < 0){
				xx = -xx;
			}
			if ((y+yy) > height){
				yy = -yy + 1;
			}
			x += xx;
			y += yy;
			yy += 1;
			
			pset(x, y);
			mainLabel.repaint();
			
			try{
				Thread.sleep(interval);
			}catch(Exception e){}
		}
	}
	
	/**
	 * 
	 * @param label		メインラベル
	 * @param x			X座標初期値
	 * @param y			Y座標初期値
	 * @param xx		X移動量(固定)
	 * @param yy		Y移動量初期値
	 * @param interval	sleep時間
	 * @param color		ボール色
	 */
	public ColorBall(JLabel label, int x, int y, int xx, int yy, int interval, Color color){
		mainLabel = label;
		ImageIcon ii = (ImageIcon)mainLabel.getIcon();
		width = ii.getIconWidth();
		height = ii.getIconHeight();
		g = (Graphics2D)ii.getImage().getGraphics();
		
		init(x, y, xx, yy, interval, color);
	}
	
	private void init(int x, int y, int xx, int yy, int interval, Color color){
		this.x = x;
		this.y = y;
		this.xx = xx;
		this.yy = yy;
		this.color = color;
		this.interval = interval;
	}

	private void preset(int x, int y){
		g.setColor(Color.WHITE);
		g.fillOval(x, y, 8, 8);
	}

	private void pset(int x, int y){
		g.setColor(color);
		g.fillOval(x, y, 8, 8);
	}
	
	public static void main(String[] args){
		JFrame frame = new JFrame();
		frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
		frame.setSize(400, 400);
		Image img = new BufferedImage(400, 400, BufferedImage.TYPE_INT_RGB);
		Graphics2D g = (Graphics2D)img.getGraphics();
		g.setColor(Color.WHITE);
		g.fillRect(0, 0, 400, 400);
		JLabel mainLabel = new JLabel(new ImageIcon(img));
		frame.add(mainLabel);
		frame.setVisible(true);
		
		new ColorBall(mainLabel, 0, 40, 5, 0, 10, Color.RED).start();		// 赤ボール
		new ColorBall(mainLabel, 0, 60, 3, 0, 20, Color.YELLOW).start();	// 黄色ボール
		new ColorBall(mainLabel, 0, 120, 1, 0, 30, Color.GREEN).start();	// 緑ボール
		// 以降追加したらどんどんボールが増える
	}
}