Buttons to save and open text file in processing 3

hello guys i am a beginner in processing 3 and i want to do some complex programming need your help

i want to create 2 buttons 1. which can save the data in text file and 2.which can open that text file in notepad.

i am using following code but i saves the txt file only in the sketch file and i need to save it on my desired location and can open file using that path.

PrintWriter output;

void setup() {
  // Create a new file in the sketch directory
size(500,500);
  output = createWriter("positionnew.txt"); 


}

void draw() {

  point(mouseX, mouseY);
  output.println(mouseX + "t" + mouseY); // Write the coordinate to the file

}


void keyPressed() {
  output.flush(); // Writes the remaining data to the file
  output.close(); // Finishes the file
  exit(); // Stops the program
}
1 Like

Hello!

That example below should get you started.

For a button see https://www.processing.org/examples/button.html

Additionally to open currentFile in NotePad (in Windows!) :


void openInNotepad() {
  // open in notepad

  try
  {
    ProcessBuilder pb = new ProcessBuilder("notepad.exe", currentFile, "");
    Process p = pb.start();
  }
  catch ( Exception /* IOException, URISyntaxException */ e )
  {
    e.printStackTrace();
  }//catch
}//
//

Regards, Chrisir

Example


// http://forum.processing.org/topic/beginner-s-question-an-application-software-with-source-code-made-with-processing
//
import java.io.File;

// current text 
String input = "";

// file name as String
String currentFile = ""; 

// cursor sign blinks 
boolean cursorBlinkFlag;  // on/off 
int timerCursorBlink;     // timer 

//---------------------------------------------------------------------------

void setup() {
  size(880, 800);
}

void draw() {
  background(111);

  text ("Type something"
    +"                                                           "
    +"Commands: F3 to open; F2 to save changes; F12 to save a new file; F10 New (deletes text); Alt-F4 to quit.", 10, 30 );
  text ("current file : " 
    + textOfCurrentFile(), 10, 50);

  text (input + strBlink(), 10, 70);
}

//---------------------------------------------------------------------------
// Inputs 

void keyPressed() {
  // Is the key CODED? 
  if (key==CODED) {
    // key is CODED --------------------------------------------
    if ( keyCode == java.awt.event.KeyEvent.VK_F3 ) {
      // open 
      load();
    } else if ( keyCode == java.awt.event.KeyEvent.VK_F2  ) {
      // save existing file
      if  ( !currentFile.equals("") ) {
        // save existing file
        saveExistingFileThatHasBeenChanged();
      } else { 
        // no file to save to, 
        // save new File 
        save();
      }
    } else if ( keyCode == java.awt.event.KeyEvent.VK_F10  ) {
      // delete
      input = "";
      currentFile = "";
    } else if ( keyCode == java.awt.event.KeyEvent.VK_F12  ) {
      // save new File 
      save();
    } else 
    {
      // do nothing
    }
    //
  } // if --------------------------------------------
  else  
  { // key is not CODED --------------------------------------------
    if (key==BACKSPACE) {
      // shorten
      if (input.length()>0)
        input=input.substring(0, input.length()-1);
    } else if (key==ESC) {
      // kill Esc
      key=0;
    } else {
      // add key (normal writing) 
      input+=key;
    } // else
    //
  } // else  // key is not CODED -----------------------------------------------
  //
} // func

// ------------------------------------------------------
// Load

void load() {
  File folderToStartFrom = new File( dataPath("") + "//*.*" ); 
  selectInput("Select a file to open", "fileSelectedOpen", folderToStartFrom );
}

void fileSelectedOpen(File selection) {
  if (selection == null) {
    println("Window was closed or the user hit cancel.");
  } else {
    println("User selected " + selection.getAbsolutePath());
    currentFile=selection.getAbsolutePath();
    input = join ( loadStrings( selection.getAbsolutePath() ), "\n" );
  }//else
}

// ---------------------------------------------------------
// Save As.... 

void save() {
  selectOutput("Select a file to write to:", "fileSelectedWrite");
}

void fileSelectedWrite(File selection) {
  if (selection == null) {
    println("Window was closed or the user hit cancel.");
  } else {
    println("User selected " + selection.getAbsolutePath());
    // Do we have a txt at the end? 
    if (selection.getName().length() < 4 || selection.getName().indexOf(".txt") != selection.getName().length()-4 ) {
      // problem missing ".txt"
      currentFile = selection.getAbsolutePath()+".txt"; // very rough approach...
    } else {
      currentFile = selection.getAbsolutePath();
    }//else 
    String[] lines = new String[0];  
    lines = append ( lines, input ); 
    // Writes the strings to a file, each on a separate line
    saveStrings( currentFile, lines);
  }
}
// ---------------------------------------------------------
// Save existing file

void saveExistingFileThatHasBeenChanged() {
  println("saveExistingFileThatHasBeenChanged");
  // Writes the strings to a file, each on a separate line (overwriting)
  String[] lines = new String[0];  
  lines = append ( lines, input ); 
  saveStrings( currentFile, lines );
}

// ---------------------------------------------------------
// Tools

String textOfCurrentFile() {
  if (currentFile.equals(""))
    return "<Not a file>"; 
  else 
  return currentFile;
}

String strBlink() {
  // manage and show the Blinking Cursor |

  // timer to toggle the flag cursorBlinkFlag
  if (millis()-timerCursorBlink > 330) {
    cursorBlinkFlag  = !cursorBlinkFlag; // toggle
    timerCursorBlink = millis(); // set timer
  }//if

  // return the line "|" or nothing 
  if (cursorBlinkFlag) 
    return"|";
  else return"";
}//func 
//
1 Like

can you give an example for this code ?

The code is derived from here:

https://www.processing.org/reference/selectInput_.html

As you can see, there is a way to call selectInput as

selectInput(prompt, callback, file)

That’s what I did in my sketch: tell selectInput in which folder to start

You can also specify *.txt and so on

see also

https://docs.oracle.com/javase/7/docs/api/java/io/File.html

dataPath

dataPath("") and sketchPath("") return the 2 paths

New version

1 Like

rn i have 3 problems:-
1.
i am trying to use buttons for red and green for on and off and if button is on then value=value-10 else value remains same but the value is decreasing by 10 continuously what should i do?

2.i have add radio button but dont know how to perform operation on them
like…if 1 is selected value=value +10

how can i use multiple window ?

For 1 and 2 show your entire code

For 3 see controlp5 docu or g4p docu

Maybe you have the wrong kind of button

you want to happen something only once on click not throughout

So the button shouldn’t have a on and off but just be clickable and reacting once

thanks that was really helpful my 1st problem has been solved

import controlP5.*;

RadioButton passengers;

ControlP5 cp8;

passengers=cp8.addRadioButton(“No of people”, 104, 36).setPosition(400, 300);
passengers.setSize(20, 20);
passengers.setColorForeground(color(255));
passengers.setColorActive(color(100));
passengers.setColorBackground(color(180));
passengers.setSpacingRow(4);
passengers.addItem(“1”, 1);
passengers.addItem(“2”, 2);
passengers.activate(1);

////***********************************//

in this code i want to perform operation that if 1 is select then print("hello
");
if 2 is select the Hello

did you read this:

http://www.sojamo.de/libraries/controlP5/examples/controllers/ControlP5radioButton/ControlP5radioButton.pde

this seems to be important:

void radioButton(int a) {
  println("a radio Button event: "+a);
}

full code:


/**
 * ControlP5 RadioButton
 *
 *
 * find a list of public methods available for the RadioButton Controller
 * at the bottom of this sketch.
 *
 * by Andreas Schlegel, 2012
 * www.sojamo.de/libraries/controlp5
 *
 */


import controlP5.*;

ControlP5 cp5;

int myColorBackground = color(0, 0, 0);

RadioButton r;

void setup() {
  size(700, 400);

  cp5 = new ControlP5(this);
  r = cp5.addRadioButton("radioButton")
    .setPosition(20, 160)
    .setSize(40, 20)
    .setColorForeground(color(120))
    .setColorActive(color(255))
    .setColorLabel(color(255))
    .setItemsPerRow(5)
    .setSpacingColumn(50)
    .addItem("50", 1)
    .addItem("100", 2)
    .addItem("150", 3)
    .addItem("200", 4)
    .addItem("250", 5)
    ;

  //for (Toggle t : r.getItems()) {
  //  t.captionLabel().setColorBackground(color(255, 80));
  //  t.captionLabel().style().moveMargin(-7, 0, 0, -3);
  //  t.captionLabel().style().movePadding(7, 0, 0, 3);
  //  t.captionLabel().style().backgroundWidth = 45;
  //  t.captionLabel().style().backgroundHeight = 13;
  //}
}


void draw() {
  background(myColorBackground);
}


void keyPressed() {
  switch(key) {
    case('0'): 
    r.deactivateAll(); 
    break;
    case('1'): 
    r.activate(0); 
    break;
    case('2'): 
    r.activate(1); 
    break;
    case('3'): 
    r.activate(2); 
    break;
    case('4'): 
    r.activate(3); 
    break;
    case('5'): 
    r.activate(4); 
    break;
  }
}

void controlEvent(ControlEvent theEvent) {
  if (theEvent.isFrom(r)) {
    print("got an event from "+theEvent.getName()+"\t");
    for (int i=0; i<theEvent.getGroup().getArrayValue().length; i++) {
      print(int(theEvent.getGroup().getArrayValue()[i]));
    }
    println("\t "+theEvent.getValue());
    myColorBackground = color(int(theEvent.group().getValue()*50), 0, 0);
  }
}

void radioButton(int a) {
  println("a radio Button event: "+a);
}
//