import java.io.File; import java.io.FileNotFoundException; import java.io.IOException; import java.io.PrintWriter; import java.util.ArrayList; import java.util.Scanner; import javafx.scene.canvas.Canvas; import javafx.scene.canvas.GraphicsContext; import javafx.scene.paint.Color; public class MyCanvas extends Canvas { private double width, height; // Canvas has them, as private private GraphicsContext gc; // Canvas has it, as private private ArrayList strokes; public MyCanvas(double w, double h) { super(w, h); width = w; height = h; gc = super.getGraphicsContext2D(); strokes = new ArrayList<>(); } public void addStroke(Stroke s) { strokes.add(s); // must repaint paint(); } public void clearCanvas() { strokes.clear(); paint(); } public void paint() { // clear canvas gc.clearRect(0, 0, width, height); // draw all strokes in the arraylist for (Stroke s : strokes) { s.draw(gc); } } public void openTextFile(File fh) { try { Scanner fileIn = new Scanner(fh); clearCanvas(); // read the number of strokes in the file int nStrokes = fileIn.nextInt(); for (int i = 0; i < nStrokes; ++i) { String type = fileIn.next(); int cx = fileIn.nextInt(); int cy = fileIn.nextInt(); int size = fileIn.nextInt(); boolean fill = fileIn.nextBoolean(); double red = fileIn.nextDouble(); double green = fileIn.nextDouble(); double blue = fileIn.nextDouble(); Color color = Color.color(red, green, blue); // based on the stroke type, create different strokes Stroke s = null; if (type.equals("C")) { s = new CircularStroke(cx, cy, size, fill, color); } else if (type.equals("S")) { s = new SquareStroke(cx, cy, size, fill, color); } if (s != null) { strokes.add(s); } } paint(); fileIn.close(); } catch(FileNotFoundException e1) { System.err.println(fh.getName() + " not found in the current folder"); e1.printStackTrace(); } catch(Exception e3) { System.err.println("Some error loading a drawing from " + fh.getName()); e3.printStackTrace(); } } // allows user to save current drawing (canvas) into a text file // format: // #_of_strokes // C cx cy size filled r g b // S cx cy size filled r g b public void saveTextFile(File fh) { try { PrintWriter fileOut = new PrintWriter(fh); fileOut.println(strokes.size()); for (Stroke s : strokes) { fileOut.println(s.toString()); } fileOut.close(); } catch(IOException e) { System.err.println("Error writing to " + fh.getName()); e.printStackTrace(); } } }