Create a Open File Button in Processing

While I am creating an Open File button using selectInput(). The problem is that the program keeps opening windows every time a user selects a file. How do I prevent this from happening?

<

pre lang="processing"> void setup() { size(500, 500); background(255); }

void draw() { noStroke(); fill(255, 0, 0); rect(0, 0, 50, 20);

if (mousePressed) { if (mouseX <= 50 && mouseY <= 20) { selectInput("Select a file to open:", "fileSelected"); } } }

void fileSelected(File selection) { if (selection != null) { String absolutePath = selection.getAbsolutePath(); String[] locations = split(absolutePath, "\"); String fileName = locations[locations.length - 1];

//addFile(fileList);
println(fileName);

} }

Tagged:

Answers

  • edited July 2015 Answer ✓

    Instead of checking the mousePressed variable in draw() : if (mousePressed) { if (mouseX <= 50 && mouseY <= 20) { selectInput("Select a file to open:", "fileSelected"); } } } put that peace of code inside void mousePressed(){} (It executes a code just once, instead of draw() that loops many times per second)

  • I would also recommend a global marker that tells you, if something was loaded

    boolean somethingWasLoaded = false;

    then you can say in draw

    void draw() { 
    
    if (somethingWasLoaded) {
    
    // do something with the file 
    
    }
    
    else 
    
    {
    
    // wait 
    
    noStroke(); 
    
    fill(255, 0, 0); 
    
    rect(0, 0, 50, 20);
    
    }
    
    }
    
Sign In or Register to comment.