Save/Load an ArrayList file of PGraphics To/From a text file
in
Programming Questions
•
2 months ago
I'm hoping for a little direction on something. In a sketch I create an ArrayList of PGraphics, starting with just one image. The image can be drawn on with the mouse. Using the right arrow key you can create a new PGraphics and draw on that as well. The right and left keys serve to flip between the PGraphics. I would like to create a function to save all of the PGraphics to a file and another function to load them again.
I've been looking around for info on this and have some ideas, but nothing has been obvious enough for me to understand. Any help would be appreciated. Here is the simplified code of what I am working on:
- int currentPage = 1;
- ArrayList<PGraphics> pageCollection = new ArrayList<PGraphics>();
- void setup(){
- size(400,400);
- background(255);
- pageCollection.add(createGraphics(300,300));
- pageCollection.get(0).beginDraw();
- pageCollection.get(0).background(200);
- pageCollection.get(0).endDraw();
- }
- void draw(){
- frame.setTitle("Page " + currentPage + " of " + pageCollection.size());
- background(255);
- image(pageCollection.get(currentPage-1),50,50);
- g.removeCache(pageCollection.get(currentPage-1)); //memory leak prevention
- }
- void mouseDragged() {
- makeMark();
- }
- void makeMark() {
- pageCollection.get(currentPage-1).beginDraw();
- pageCollection.get(currentPage-1).smooth();
- pageCollection.get(currentPage-1).stroke(0);
- pageCollection.get(currentPage-1).line(pmouseX-50,pmouseY-50,mouseX-50,mouseY-50);
- pageCollection.get(currentPage-1).endDraw();
- }
- void keyPressed() {
- switch (keyCode) {
- case LEFT: //scroll left through pages
- println("###### Go Back One Page ######");
- if (currentPage == 1){
- currentPage = 1;
- }else {
- currentPage -=1;
- }
- break;
- case RIGHT: //scroll right through pages
- println("###### Go Forward or Add One Page ######");
- if (currentPage < 300) {
- if (currentPage == pageCollection.size()){
- newPage();
- }else {
- currentPage +=1;
- }
- }
- break;
- case UP: // save the ArrayList to file
- println("###### Save All Pages ######");
- // call save function
- savePages();
- break;
- case DOWN: // clear the current ArrayList and load a file into ArrayList
- println("###### Load Pages ######");
- loadPages();
- break;
- default:
- println("###### keyCode error ######");
- }
- }
- void newPage() {
- pageCollection.add(createGraphics(300,300));
- pageCollection.get(currentPage).beginDraw();
- pageCollection.get(currentPage).background(200);
- pageCollection.get(currentPage).smooth();
- pageCollection.get(currentPage).stroke(0);
- pageCollection.get(currentPage).endDraw();
- currentPage +=1;
- }
- void savePages() {
- // code for saving pages to a text file
- }
- void loadPages() {
- // code for clearing the current ArrayList and loading the ArrayList from a text file
- }
1