selectInput() and while() loop headaches in Processing 2.2.1

I’ve been working on a Processing sketch that uses a selectInput() dialogue to ask for a CSV file. The example in the Processing reference doesn’t work very well because the sketch doesn’t pause and wait for you to select the input. It opens a open-file window and then immediately skips on to running rest of the code before you’ve selected your file, which predictably crashes because it contains references to a file that hasn’t been selected yet and so resolve to null.

A solution proposed on the forums is to add a while() loop after selectInput() which pauses the sketch while the selected file == null. As soon as you’ve selected the file you want to work with this ends the while() loop and the rest of the sketch proceeds with the selected file, like so: 

String sourceFile = “pause”;

selectInput(“Select a file to process:”, “fileSelected”);  // select an AMDIS results file to process – MUST BE A CSV
while(sourceFile.equals(“pause”)) {}  // wait until a file is selected

This used to work in a previous version of the sketch I wrote but I’ve recently updated Processing to 2.2.1 and, of, course things that used to work now don’t. Grrrrrrr. This might be something to do with there needing to be at least one statement. For eg, if I put a println() statement in there it simply keeps printing the same thing until I’ve selected a file. This makes the while() loop fulfil its function in pausing the sketch but the looped process of printing a zillion strings to the terminal burns up processor time and can even make the whole sketch hang. An inelegant solution. 

As an alternative a post on StackOverflow (which is the most amazing hacking resource, by the way) offered an alternative code snippet utilising a different file open dialogue from the javax.swing library. This works perfectly, if still eccentrically as it uses the old XP style file open dialogue which defaults to the location of the desktop and requires much clicking if you happen to have a deep folder structure. As a plus though it allows you to use shortcuts to navigate, unlike the native Windows 7 file open dialogue, so a quick shortcut link to your data folder plonked on the desktop facilitates rapid access to your target. 

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s