Open Files through a GUI
From Processing
If you keep writing applications that use lots of different files on your computer, you might feel constrained by first having to add them to your sketch data folder. One solution to this is to add a file browser to the sketch so that it prompts the user for which file to load. Note that this approach means your sketch will not work properly as an applet, but it can be useful nevertheless.
Contents |
Which GUI Library?
Swing is the pure Java GUI library, an alternative to AWT. AWT was Sun's first attempt at a cross-platform GUI and in some cases looks better because it calls the native OS's graphical widgets. In Swing, Java is responsible for drawing everything itself, so it can look a little different to your standard applications. However, because AWT uses native code then you must be careful how you handle it as it can disrupt your application. Because of this, and because Swing opens its file dialog in the user's home folder by default, we'll use Swing here to show how to open a JFileChooser. You might also try AWT's FileDialog yourself to compare the results.
Look and Feel
By default Swing uses its own cross-platform look and feel.
It can be made to look like the file choosers on your platform with one line of code. Unfortunately that line might throw an Exception, so it's actually six lines here:
Source code
/** filechooser taken from http://processinghacks.com/hacks:filechooser @author Tom Carden */ import javax.swing.*; // set system look and feel try { UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName()); } catch (Exception e) { e.printStackTrace(); } // create a file chooser final JFileChooser fc = new JFileChooser(); // in response to a button click: int returnVal = fc.showOpenDialog(this); if (returnVal == JFileChooser.APPROVE_OPTION) { File file = fc.getSelectedFile(); // see if it's an image // (better to write a function and check for all supported extensions) if (file.getName().endsWith("jpg")) { // load the image using the given file path PImage img = loadImage(file.getPath()); if (img != null) { // size the window and show the image size(img.width,img.height); image(img,0,0); } } else { // just print the contents to the console // note: loadStrings can take a Java File Object too String lines[] = loadStrings(file); for (int i = 0; i < lines.length; i++) { println(lines[i]); } } } else { println("Open command cancelled by user."); }
Related Links
- How to Use File Choosers from Creating a GUI with JFC/Swing.
- Processing forum discussion on file choosers