I’m trying to figure out how to make the selectFolder() function open using a select path eg instead of opening up with the documents folder selected open with the sketch paths one?
hi
This may help
Hello,
References:
- https://processing.org/reference/selectFolder_.html
- Java.io.File Class in Java - GeeksforGeeks
- https://processing.github.io/processing-javadocs/core/processing/core/PApplet.html#selectFolder-java.lang.String-java.lang.String-java.io.File-
I was able to use the File datatype for file using this syntax for selectFolder():
selectFolder(prompt, callback, file)
And set the default path to c:\test:
:)
//Processing Example for Loading Files · GitHub
// This is the Filetype we're gonna look for
String extensionToLookFor = ".jpg";
// ArrayList of loadedFiles
ArrayList<File> loadedFiles;
int fileToLoad = 0;
PImage loadedImage;
void setup()
{
size(400,300);
background(0);
//selectFolder(String, String);
selectFolder();
}
void draw()
{
if(loadedImage == null || loadedFiles == null || loadedFiles.size() <= 0)
return;
background(0);
image(loadedImage, 0, 0, width, height);
}
void keyPressed()
{
switch(key)
{
case ' ':
fileToLoad ++;
if(fileToLoad >= loadedFiles.size())
fileToLoad = 0;
String imgPath = loadedFiles.get(fileToLoad).getAbsolutePath();
println("Load: " + imgPath);
loadedImage = loadImage(imgPath);
break;
case 'l':
selectFolder();
break;
}
}
void selectFolder()
{
// Opens Window to select a folder or file from
// then Calls a Method with the selected File as Parameter
selectFolder("Select a Folder", "loadFiles");
}
void loadFiles(File selection)
{
// if nothing was selected
if(selection == null)
{
println("User hit cancel");
// open the Window again
selectFolder();
// and skip all code below by returning
return;
}
// this is the absolutePath (just for Debugging)
String selectedPath = selection.getAbsolutePath();
println("Path selected: " + selectedPath);
// now get all Files with the right Extension
loadedFiles = getFilesFromFolder(selection, extensionToLookFor);
println("Found Files: " + loadedFiles.size());
fileToLoad = 0;
loadedImage = loadImage(loadedFiles.get(fileToLoad).getAbsolutePath());
//loadedImages = loadImagesFromFiles(loadedFiles);
}
// Method that returns all Files with a specific Extension in a Folder
ArrayList<File> getFilesFromFolder(File selectedFolder, String extension)
{
// all files
File[] allFiles = selectedFolder.listFiles();
// only Files with the extension:
ArrayList<File> files = new ArrayList<File>();
// loop all Files
for (int i = 0; i < allFiles.length; i++)
{
File f = allFiles[i];
// skip files without the right extension
if( !hasExtension(f, extension) ) continue;
// if not skipped -> add it to arraylist
files.add(f);
}
// return found files
return files;
}
// Helper Method to check for a files Extension
boolean hasExtension(File file, String extension)
{
// the absolute path to the file
String filePath = file.getAbsolutePath();
// make the Path and the Extension to LowerCase (because ".JPG" == ".jpg" !!!)
filePath.toLowerCase();
extension.toLowerCase();
// get the last characters of the path as they should contain the extension of the file
// like for example: /someFolder/someFile.jpg
// last character minus the length of the extension = index of first extension char
int extensionStart = filePath.length() - extension.length();
// index of last char in filePath
int extensionEnd = filePath.length();
// just the last chars of the filePath:
String filePathExtension = filePath.substring( extensionStart, extensionEnd );
// if the filePathExtension = is the extension we're looking for
if(filePathExtension.equals(extension))
{
// end here with true
println("Right Extension: " + extension);
return true;
}
else
println("Wrong Extension: " + filePathExtension);
// file has not the extension we looked for
return false;
}
// Unused Methods:
// Method for Loading all Files in PImage ArrayList
// Beware: might be very memory consuming
ArrayList<PImage> loadImagesFromFiles(ArrayList<File> files)
{
ArrayList<PImage> imgs = new ArrayList<PImage>();
for(File f : files)
{
PImage img;
String imgPath = f.getAbsolutePath();
println("Load Image: " + imgPath);
img = loadImage(imgPath);
imgs.add(img);
}
return imgs;
}
// to be checked out:
// https://processing.org/discourse/beta/num_1212084677.html
/*
// have a look in the data folder
java.io.File folder = new java.io.File(dataPath(""));
// this is the filter (returns true if file's extension is .jpg)
java.io.FilenameFilter jpgFilter = new java.io.FilenameFilter() {
boolean accept(File dir, String name) {
return name.toLowerCase().endsWith(".jpg");
}
};
// list the files in the data folder
String[] filenames = folder.list(jpgFilter);
*/
Yeah, well, under Win it’s not reliable.
I think there’s a bug
It stores the last folder but when you open another folder inbetween it won’t return to the folder from the actual command
So you first think it works until you open another folder
I did not observe any issues.
If there is a bug can you open an issue on Github please?
:)
Hi I know this is an old thread, but how did you do this? I was about to post this exact question. I looked at the references you shared but cannot see how to accomplish it…
Thanks,
Mike
I found the example:
//import java.io.*; //import java.io.File; already imported by Processing!
File a = new File("d:/test"); // The folder must exist!
void setup() {
size(200, 200);
//selectFolder("Select a folder to process:", "folderSelected");
//selectFolder(prompt, callbackMethod, defaultSelection, callbackObject, parentFrame)
selectFolder("Select a folder to process:", "folderSelected", a);
}
void folderSelected(File selection) {
if (selection == null) {
println("Window was closed or the user hit cancel.");
} else {
println("User selected " + selection.getAbsolutePath());
}
}
void draw()
{
}
void keyPressed()
{
selectFolder("Select a folder to process:", "folderSelected", a);
}
:)
here is an Editor with 3 Mouse Buttons that shows
save and load
// Editor
// from https : // forum.processing.org/two/discussion/comment/112902/#Comment_112902
// editor path and file extension
final String pathFolder = "texts";
final String fileExtension = ".txt";
// editor content
String strText = "Test ";
// states of the program:
// unique constants:
final int NORMAL = 0;
final int SAVE = 1;
final int LOAD = 2;
///current state (must be one of them)
int state=NORMAL;
// blinking cursor:
boolean blinkIsOn=true;
// Paths
String savePath="";
String loadPath="";
// ------------------------------------------------
// Core functions of processing
void setup() {
size(900, 900);
}//func
void draw() {
switch (state) {
case NORMAL:
drawForStateNormal() ;
break;
case SAVE:
// wait for Save Dialog
waitForSaveDialog();
break;
case LOAD:
// wait for Load Dialog
waitForLoadDialog();
break;
default:
//Error
println("Fail");
exit();
break;
//
}//switch
}//func
// ------------------------------------------------
void drawForStateNormal() {
background(0);
textSize(14);
// title
fill(255, 2, 2);
text("My little Editor",
width-123, 20, 100, 422);
// show the text the user entered
fill(255);
text(strText+blink(),
20, 20, width-170, height-20);
// ----------------------
// buttons
textSize(11);
fill(128);
if ( overSave() ) {
fill(196);
}
rect(width-40, height-20, 40, 20);
fill(255);
text("Save",
width-40+7, height-9+5);
// ---
fill(128);
if ( overLoad() ) {
fill(196);
}
rect(width-40, height-50, 40, 20);
fill(255);
text("Load",
width-40+7, height-50+9+5);
// ---
fill(128);
if ( overNew() ) {
fill(196);
}
rect(width-40, height-80, 40, 20);
fill(255);
text("New",
width-40+7, height-80+9+5);
}
//----------------------------------------------------------------------------
// functions to register if mouse is over buttons
boolean overSave() {
return( mouseX > width-40 &&
mouseY > height-20 );
}
boolean overLoad() {
return( mouseX > width-40 &&
mouseY > height-50 &&
mouseY < height-50+25 );
}
boolean overNew() {
return( mouseX > width-40 &&
mouseY > height-80 &&
mouseY < height-80+25 );
}
// ---------------------------------------------------------------------------
// Inputs
void keyPressed() {
if (state!=NORMAL)
return; // !!!
// for the editor: ---------------------------------------
if (key == CODED) {
if ( keyCode == DELETE || keyCode == BACKSPACE ) {
if ( strText.length() > 0 ) {
strText = strText.substring(0, strText.length()-1);
}
}
return; // !!!
}
// key != CODED -------------------------------
if (key==ESC) {
key=0; // kill ESC
} else {
strText += key; // add to text
}// else
//
}//func
void mousePressed() {
if (state!=NORMAL)
return;
// for the buttons
if ( overSave() ) {
initSave();
}
//---
else if ( overLoad() ) {
initLoad();
}
//---
else if ( overNew() ) {
strText="";
}
//
}//func
// -------------------------------------------------
// Save and load
void initSave() {
// init save process
// reset
savePath="";
// make date time stamp (the expression nf(n,2) means leading zero: 2 becomes 02)
String dateTimeStamp = year()
+ nf(month(), 2)
+ nf(day(), 2)
+ "-"
+ nf(hour(), 2)
+ nf(minute(), 2)
+ nf(second(), 2);
// prepare fileDescription which occurs in the dialogue
File fileDescription = new File( sketchPath()
+ "//"
+ pathFolder
+ "//"
+ dateTimeStamp
+ fileExtension);
// open the dialog
selectOutput("Select a file to write to", "fileSelectedSave", fileDescription);
// set state to wait
state=SAVE;
}
void initLoad() {
// init load process
// reset
loadPath="";
// prepare fileDescription which occurs in the dialogue
File fileDescription = new File( sketchPath()+"//"+pathFolder+"//"+"*" + fileExtension );
// open the dialog
selectInput("Select a file to load", "fileSelectedLoad", fileDescription);
// set state to wait
state=LOAD;
}
void fileSelectedSave(File selection) {
// the 'callback' function
if (selection == null) {
// println("Window was closed or the user hit cancel.");
// go back
state=NORMAL;
} else {
// println("User selected " + selection.getAbsolutePath());
savePath=selection.getAbsolutePath();
}
}
void fileSelectedLoad(File selection) {
// the 'callback' function
if (selection == null) {
// println("Window was closed or the user hit cancel.");
// go back
state=NORMAL;
} else {
// println("User selected " + selection.getAbsolutePath());
loadPath=selection.getAbsolutePath();
}
}
void waitForSaveDialog() {
if (!savePath.equals("")) {
// waiting is over
saveIt();
// go back
state=NORMAL;
}
}
void waitForLoadDialog() {
if (!loadPath.equals("")) {
// waiting is over
loadIt();
// go back
state=NORMAL;
}
}
void saveIt() {
// save
// split at line break and make array (to save it)
String[] strs = split ( strText, "\n" );
// check if file extension (fileExtension, e.g. .txt) is there
int len = savePath.length();
if (len<4 || !savePath.substring( len-4 ).equals(fileExtension)) {
// file Extension is not present, we have to add it
savePath += fileExtension; // add the file Extension
}
// save
println("Saved: " + savePath);
saveStrings( savePath, strs );
}
void loadIt() {
// load
String[] strs = loadStrings( loadPath );
strText = join(strs, "\n");
}
// -------------------------------------------------
// Misc
String blink() {
// toggle blinkIsOn
if (frameCount%17 == 0)
blinkIsOn=!blinkIsOn;
// depending from blinkIsOn
if (blinkIsOn)
return "|";
else return "";
}
//
Take notice Processing already provides many functions that return a File object, which can be invoked as soon as callback settings():
Any of those 3 functions can be used as the 3rd argument for selectFolder(): PApplet
I really liked this example - it’s so clean and simple to implement!
I also appreciated your JChooser example, but I like this one better because it sticks with Processing only and doesn’t delve into swing.
Thank you so much!
Mike
It’s an amazing little program! I admit I couldn’t figure out yet how to use it, but there seems to be a wealth of gems in it!
thank you!
Interesting thing…I modified @glv’s example, hoping to be able to use it to import a file from a certain folder.
But it works intermittently. If I run it and press enter, it goes to the parent folder. Then if I cancel and hit enter, it goes to the exact folder.
If I hit enter again, it goes to the parent, and if I cancel and hit enter, it goes to the exact folder…
over and over…
why?
here’s the code:
//import java.io.*; //import java.io.File; already imported by Processing!
File a = new File("/Users/UserName/Documents/Processing/SceneEditorV1_1_01/Backups"); // The folder must exist!
void setup() {
size(200, 200);
//selectFolder("Select a folder to process:", "folderSelected");
//selectFolder(prompt, callbackMethod, defaultSelection, callbackObject, parentFrame)
//selectFolder("Select a folder to process:", "folderSelected", a);
}
void folderSelected(File selection) {
if (selection == null) {
println("Window was closed or the user hit cancel.");
} else {
println("User selected " + selection.getAbsolutePath());
}
}
void draw()
{
}
void keyPressed()
{
selectInput("Select a backup file:", "folderSelected", a);
}
Anyone can see any reason it would go back and forth from parent to exact folder, over and over?
W10
Processing 4.3
This example works with consistency here:
< Click here to open !
void setup()
{
}
void draw()
{
}
void mousePressed()
{
String path = sketchPath();
path = "E:\\Pictures\\2017-08-10\\Set 01"; // Set an existing path on your system
println(path);
File f = new File(path);
println(f.getAbsolutePath());
selectInput("open file", "openFile", f);
}
void openFile(File selection)
{
println("File selected:", selection);
}
This text will be hidden
Improved version of above:
< Click here to open !
/*
Project: selectInPut() to a default folder
Author: GLV
Date: 2024-08-25
Version: 1.0.1
*/
// Addresses dialog behind sketch window:
// https://github.com/processing/processing/issues/3775
//import processing.javafx.*; // If using this renderer
PImage img;
void setup()
{
size(800, 600);
//size(800, 600, FX2D);
//size(800, 600, P2D);
//size(800, 600, P3D);
noLoop();
}
void draw()
{
if(img != null)
{
img.resize(width, height);
image(img, 0, 0);
}
}
void mousePressed()
{
surface.setVisible(false);
String path = sketchPath();
//path = "E:\\Pictures\\2017-08-10\\Set 01\\*"; // Set an existing path on your system
String username = System.getProperty("user.name");
path = "D:\\users\\" + username + "\\Pictures\\*"; // Set path to pictures. May differ on your PC.
//println(path);
File f = new File(path);
println(f.getAbsolutePath());
selectInput("open file", "openFile", f);
}
void openFile(File selection)
{
if (selection != null)
{
println("File selected:", selection);
String s = selection.toString();
img = loadImage(s);
}
surface.setVisible(true);
redraw();
}
Related Processing 4.3 Github Issue:
:)
Thank you so much @glv. I so appreciate all your time and dedication to excellence!!!
I will test it out and again, THANKS!!!