import javax.swing.*;
import java.util.*;
import java.awt.*;
import java.awt.event.*;
import java.awt.geom.*;
import java.io.*;

class PannelloGrafico extends JPanel
{
	int xPos, yPos, w, h;
	ArrayList cerchi;
	
	public PannelloGrafico()
	{
		cerchi = new ArrayList();
		addMouseListener(new MouseAdapter(){ 
			public void mousePressed(MouseEvent e) {
				xPos = e.getX();
				yPos = e.getY(); }
			public void mouseReleased(MouseEvent e) {
				w = e.getX() - xPos;
				h = e.getY() - yPos;
				cerchi.add(new Ellipse2D.Double(xPos, yPos, w, h));
				repaint(); }
			});
	}

	public void salva()
	{
		FileOutputStream fout;		
		try
		{
		    fout = new FileOutputStream ("cerchi.txt");
		    PrintStream scrivi = new PrintStream(fout);
		    if (cerchi != null)
		    	for (int h = 0; h < cerchi.size(); h++)
		    	{
		    		Ellipse2D cerchio = (Ellipse2D)cerchi.get(h);
		    		scrivi.println((int)(cerchio.getX()) + " " + (int)(cerchio.getY()) + " " + (int)(cerchio.getWidth()) + " " + (int)(cerchio.getHeight()));
		    	}
		    fout.close();		
		}
		catch (IOException e) { }	
	}
	public void leggi()
	{
		cerchi = new ArrayList();
		FileInputStream fin;
		try
		{
		    fin = new FileInputStream ("cerchi.txt");
		    DataInputStream filedaleggere = new DataInputStream(fin);
		    String rigaCorrente = "";
		    while(true)
		    {
		    	rigaCorrente = filedaleggere.readLine();
		    	if (rigaCorrente == null) break;
		    	StringTokenizer valori = new StringTokenizer(rigaCorrente);
		    	xPos = Integer.parseInt(valori.nextToken());
		    	yPos = Integer.parseInt(valori.nextToken());
		    	w = Integer.parseInt(valori.nextToken());
		    	h = Integer.parseInt(valori.nextToken());
		    	cerchi.add(new Ellipse2D.Double(xPos,yPos,w,h));
		    }
		    fin.close();		
		}
		catch (IOException e) { }	
	}
	
	public void paint(Graphics g)
	{
		super.paintComponent(g);
		Graphics2D g2 = (Graphics2D)g;
		if (cerchi != null)
			for (int h = 0; h < cerchi.size(); h++)
				g2.fill( (Ellipse2D)cerchi.get(h) );
	}
}
public class formedafile extends JFrame
{
	JMenuItem leggiFile, salvaFile;
	PannelloGrafico panGraf;
	
	public formedafile()
	{
		panGraf = new PannelloGrafico();

		leggiFile = new JMenuItem("Leggi");
		leggiFile.addActionListener(new ActionListener(){ public void actionPerformed(ActionEvent e){
			panGraf.leggi();
			panGraf.repaint();
			}});
		salvaFile = new JMenuItem("Salva");
		salvaFile.addActionListener(new ActionListener(){ public void actionPerformed(ActionEvent e){
			panGraf.salva();
			panGraf.leggi();
			panGraf.repaint();
			}});
	
		JMenu fileMenu = new JMenu("File");
		fileMenu.add(leggiFile);
		fileMenu.add(salvaFile);
		JMenuBar jmb = new JMenuBar();
		jmb.add(fileMenu);
		setJMenuBar(jmb);

		setSize(400,400);
		getContentPane().add(panGraf);
		setDefaultCloseOperation(EXIT_ON_CLOSE);
		setVisible(true);

	}
	public static void main(String[] args)
	{
		formedafile f = new formedafile();
	}
}