import java.awt.*;
import javax.swing.*;
import java.awt.event.*;

public class test4 extends JPanel
{
	int x = 0, y = 0;
	Palla redBall, greenBall;
	int leftSideX = 100, rightSideX = 400;
	Color leftSideColor, rightSideColor;
	
	public test4()
	{
		redBall = new Palla(150,50,30, Color.red);
		greenBall = new Palla(250,50,30, Color.green);
		
		leftSideColor = Color.red;
		rightSideColor = Color.green;
		
		addMouseListener(new MouseAdapter() { public void mousePressed(MouseEvent e){
			redBall.clicked = redBall.isClicked(e.getX(), e.getY());
			greenBall.clicked = greenBall.isClicked(e.getX(), e.getY());

			if (redBall.clicked)
			{
				x = e.getX() - redBall.x;
				y = e.getY() - redBall.y;
			}
			else
			{
				x = e.getX() - greenBall.x;
				y = e.getY() - greenBall.y;
			}
			}});
		addMouseMotionListener(new MouseMotionAdapter() { public void mouseDragged(MouseEvent e){
			if (redBall.clicked)
			{
				if (e.getX() > rightSideX)
					redBall.moveTo(rightSideX - x, e.getY() - y);
				else
					redBall.moveTo(e.getX() - x, e.getY() - y);
			}
			else if (greenBall.clicked)
			{
				if (e.getX() < leftSideX)
					greenBall.moveTo(leftSideX - x, e.getY() - y);
				else
					greenBall.moveTo(e.getX() - x, e.getY() - y);
			}
			repaint();
			}});
	}
	
	public void paint(Graphics g)
	{
		super.paintComponent(g);

		g.setColor(leftSideColor);
		g.fillRect(0,0,leftSideX, 200);
		g.setColor(rightSideColor);
		g.fillRect(rightSideX, 0, 500,200);

		redBall.mostra(g);
		greenBall.mostra(g);
	}
	
	public static void main(String[] a)
	{
		JFrame f = new JFrame();
		f.setTitle("Test 4");
		f.setSize(500,200);
		f.add(new test4());
		f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
		f.setVisible(true);
	}
}

class Palla
{
	int x, y, dim;
	Color color;
	boolean clicked = false;
	public Palla(int x, int y, int dim, Color color)
	{
		this.x = x;
		this.y = y;
		this.dim = dim;
		this.color = color;
	}
	public void mostra(Graphics g)
	{
		g.setColor(color);
		g.fillOval(x-dim/2, y-dim/2, dim, dim);
		g.setColor(Color.black);
		g.drawOval(x-dim/2, y-dim/2, dim, dim);
	}
	public void moveTo(int x, int y)
	{
		this.x = x;
		this.y = y;
	}
	public boolean isClicked(int cx, int cy)
	{
		if (cx > x-dim/2 && cx < x+dim/2 && cy > y-dim/2 && cy < y+dim/2)
			return true;
		else
			return false;
	}
}
