package sk.upjs.paz1a.cvicenie8;
import java.awt.Color;
import java.awt.event.MouseEvent;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.PrintWriter;
import java.util.Locale;
import java.util.Scanner;
import sk.upjs.jpaz2.Turtle;
import sk.upjs.jpaz2.WinPane;
public class ClickPane extends WinPane {
private int maxDotsCount = 1000;
private int[] dotsX = new int[maxDotsCount];
private int[] dotsY = new int[maxDotsCount];
private double[] dotsR = new double[maxDotsCount];
private int dotCount = 0;
protected void onMouseClicked(int x, int y, MouseEvent detail) {
if (detail.getButton() == MouseEvent.BUTTON1) {
// vykreslim bodku
Turtle painter = new Turtle();
this.add(painter);
painter.setFillColor(Color.black);
painter.setPosition(x, y);
double radius = Math.random() * 8 + 12;
painter.dot(radius);
this.remove(painter);
// ulozim bodku do pola
dotsX[dotCount] = x;
dotsY[dotCount] = y;
dotsR[dotCount] = radius;
dotCount++;
}
if (detail.getButton() == MouseEvent.BUTTON3 && !detail.isAltDown()) {
System.out.println("SAVE");
saveClicksToFile("dots.txt");
}
if (detail.getButton() == MouseEvent.BUTTON3 && detail.isAltDown()) {
System.out.println("LOAD");
loadClicksFromFile("dots.txt");
}
}
public void saveClicksToFile(String filename) {
File file = new File(filename);
PrintWriter pw = null;
try {
pw = new PrintWriter(file);
for (int i = 0; i < dotCount; i++) {
pw.println(dotsX[i] + " " + dotsY[i] + " " + dotsR[i]);
}
} catch (FileNotFoundException e) {
e.printStackTrace();
} finally {
if (pw != null) {
pw.close();
}
}
}
public void loadClicksFromFile(String filename) {
// vycistit plochu a pole
this.clear();
// nemusim mazat pole ani vytvarat nove
dotCount = 0;
Turtle painter = new Turtle();
this.add(painter);
painter.setFillColor(Color.red);
Scanner sc = null;
try {
File file = new File(filename);
sc = new Scanner(file);
sc.useLocale(Locale.US);
while(sc.hasNextInt()) {
// file -> pole
dotsX[dotCount] = sc.nextInt();
dotsY[dotCount] = sc.nextInt();
dotsR[dotCount] = sc.nextDouble();
// pole -> winpane
painter.setPosition(dotsX[dotCount], dotsY[dotCount]);
painter.dot(dotsR[dotCount]);
dotCount++;
}
} catch (FileNotFoundException e) {
e.printStackTrace();
} finally {
if (sc != null) {
sc.close();
}
}
System.out.println("odstranujem korytnacku");
this.remove(painter);
}
}