We closed this forum 18 June 2010. It has served us well since 2005 as the ALPHA forum did before it from 2002 to 2005. New discussions are ongoing at the new URL http://forum.processing.org. You'll need to sign up and get a new user account. We're sorry about that inconvenience, but we think it's better in the long run. The content on this forum will remain online.
IndexProgramming Questions & HelpPrograms › How to show a JFileChooser
Pages: 1 2 
How to show a JFileChooser (Read 4247 times)
How to show a JFileChooser
Feb 21st, 2006, 3:00am
 
Hi,

Is it possible to show a JFileChooser (from javax.swing)  in a PApplet?

My code is something like the showed down and sometimes it works, but sometimes the JFileChooser doesn't load well (when the mouse is over them just when it is showed or when the button is pressed).
Maybe I need to config an event listener or something like that but how?? thank you very much.

public void openFile()
{
 File f = null;
 JFileChooser selector = new JFileChooser(".");
 try
 {
   int value = selector.showOpenDialog(null);
   if( value == JFileChooser.APPROVE_OPTION)
   {
     f = selector.getSelectedFile();
   }

   println("file selected: "+f.getAbsolutePath() );

 }
 catch(Exception e)
 {
   e.printStackTrace();
 }
}
Re: How to show a JFileChooser
Reply #1 - Feb 23rd, 2006, 5:58am
 
rather than double posting this a second time in another topic area, try searching the board first, or at least reading recent messages. this question was answered two or three days before the first time you posted.
Re: How to show a JFileChooser
Reply #2 - Feb 23rd, 2006, 10:03am
 
Or even better, just check Processinghacks.com:

http://www.processinghacks.com/hacks/filechooser
Re: How to show a JFileChooser
Reply #3 - Feb 23rd, 2006, 11:19am
 
With the code I wrote for the processinghacks post, I have no problems if I open the JFileChooser inside setup(), but it doesn't seem to reliably handle opening from mousePressed() or inside draw().  I have the same issues you describe - sometimes it works, sometimes it doesn't.  

I'll try and track down the problem at some point, but I won't get to it right away.
Re: How to show a JFileChooser
Reply #4 - Feb 23rd, 2006, 11:54am
 
OK, had a brain wave about event despatching threads and so on.  If you use invokeLater from the SwingUtilities, your applet will continue running in the background and you shouldn't get any strange side effects from showing the JFileChooser:

Code:


void mousePressed() {

SwingUtilities.invokeLater(new Runnable() {
public void run() {
try {

JFileChooser fc = new JFileChooser();
int returnVal = fc.showOpenDialog(null);

if (returnVal == JFileChooser.APPROVE_OPTION) {
File file = fc.getSelectedFile();
String lines[] = loadStrings(file); // loadStrings can take a Java File Object too
for (int i = 0; i < lines.length; i++) {
println(lines[i]);
}
}
else {
println("Open command cancelled by user.");
}
}
catch (Exception e) {
e.printStackTrace();
}
}
});

}



If you use this method for something real (not just printing lines from a file!) you'll want to set a boolean or something to say when the file is loaded, and check that inside draw.
Re: How to show a JFileChooser
Reply #5 - Feb 23rd, 2006, 6:45pm
 
Fry,
Sorry,I did a double posting because nobody answer my question and I thought that maybe it would be better placed in the Integration category (I tried to erase first the post in this category but I could not).
I look for some informetion before posting, but I used the Search field above with "JFileChooser" and I didn't found nothing interesting or the links were wrong.
I won't do a double posting again Smiley
CONGRATULATIONS FOR PROCESSING!!
It's been a lot of useful to me (I'm a computer engineer from Spain)

watz,
Thank you for the information, I didn't knew about processinghacks!

TomC, I think our problem is out thanks to your SwingUtilities.invokeLater() idea. It works perfectly!!
Thank you very very much!

Re: How to show a JFileChooser
Reply #6 - Mar 21st, 2006, 4:36pm
 
Having trouble writing some all purpose file browser functions. I want to be able to call a function returning a PImage or null. I can't setup a local variable in the function to return the information though. I get:
Code:

Semantic Error: Invalid reference in inner class "Temporary_3524_5415$1" to a non-final local variable, "temp", declared in method "getFile".

I can patch this however:
Code:

import javax.swing.*;
PImage pimage;
PImage temp = null;
void setup(){
size(200,200);
}
void draw(){
}
void mousePressed(){
pimage = getFile();
if(pimage != null){
image(pimage, 0, 0, width, height);
}
}
PImage getFile(){
//PImage temp = null;
SwingUtilities.invokeLater(new Runnable() {
public void run() {
try {
JFileChooser fc = new JFileChooser();
int returnVal = fc.showOpenDialog(null);
if (returnVal == JFileChooser.APPROVE_OPTION) {
File file = fc.getSelectedFile();
boolean executeOperation = false;
if(file.getName().endsWith("jpg") || file.getName().endsWith("gif")){
temp = loadImage(file.getPath());

}
}
}
catch (Exception e) {
e.printStackTrace();
}
}
}
);
return temp;
}

But that means I have to have a global variable floating around that I may have to empty each time I call the function. Which looks a teeny bit unsightly, and goes against the idea of having an encapsulated function that I can copy from sketch to sketch. Is there a solution to this problem?
Re: How to show a JFileChooser
Reply #7 - Mar 21st, 2006, 4:47pm
 
that's because you're using a final class internal to the function when you do the whole "new Runnable()" thing.. you should read up on the java tutorial or whatever as to how those things work, you're stepping in advanced stuff there.

the simplest proper solution would be for the file choosing function to call another method in your sketch called "fileSelected(File what)" or "setImage(PImage what)" or something like that, rather than keeping a local variable for it. this would serve as a callback for the new thread that gets spawned by invokeLater.
Re: How to show a JFileChooser
Reply #8 - Mar 21st, 2006, 5:43pm
 
Okay. I've knocked up a workaround that is a lot simpler than my previous attempt. Plus it accounts for the fact that the fileChooser runs a little asynchronous to the mother applet.
Code:

import javax.swing.*;
PImage pimage;
String getFile = null;
void setup(){
size(200,200);
}
void draw(){
if(getFile != null){
fileLoader();
}
}
void mousePressed(){
getFile = getFileName();
}
void fileLoader(){
String ext = getFile.substring(getFile.lastIndexOf('.') + 1);
ext.toLowerCase();
if(ext.equals("jpg") || ext.equals("gif")){
pimage = loadImage(getFile);
image(pimage, 0, 0, width, height);
}
getFile = null;
}
String getFileName(){
SwingUtilities.invokeLater(new Runnable() {
public void run() {
try {
JFileChooser fc = new JFileChooser();
int returnVal = fc.showOpenDialog(null);
if (returnVal == JFileChooser.APPROVE_OPTION) {
File file = fc.getSelectedFile();
getFile = file.getPath();
}
}
catch (Exception e) {
e.printStackTrace();
}
}
}
);
return getFile;
}

I imagine there might be some cleverer way of doing this (please tell if there is) but I'm happy for now. Thanks.
Re: How to show a JFileChooser
Reply #9 - Mar 21st, 2006, 8:11pm
 
i don't think that'll actually work, because the file returned from that function will be null.

this is more along the lines of what you're looking for, and a good bit simpler:

Quote:


import javax.swing.*;

PImage image;

void setup(){
 size(200, 200);
}

void draw() {
}

void mousePressed() {
 launchChooser();
}

void launchChooser(){
 SwingUtilities.invokeLater(new Runnable() {
   public void run() {
     try {
       JFileChooser fc = new JFileChooser();
        int returnVal = fc.showOpenDialog(null);
        if (returnVal == JFileChooser.APPROVE_OPTION) {
          File file = fc.getSelectedFile();
          String name = file.getName().toLowerCase();
          if (name.endsWith(".jpg") || name.endsWith(".gif")) {
            image = loadImage(file.getAbsolutePath());
            imageChosen();
          }
        }
     } catch (Exception e) {
       e.printStackTrace();
     }
   }
 });
}

void imageChosen() {
 image(image, 0, 0, width, height);
}

you can even go fancier and pass a file name filter to the file chooser so that you can only select gif and jpg, but that's something else altogether..
Re: How to show a JFileChooser
Reply #10 - Mar 22nd, 2006, 12:34pm
 
It does work actually. I generally try to test code before posting it because my code point blank never works on the first draft. Before the return information is sent the String getFile is set. My problem related to the fact I have several file operations I wanted to go about doing. I wanted to be clever and have it all in one function, but I think you're right that I've gone about it in a pretty complicated fashion. It's my patch the patch coding style I'm afraid. I'll write it nicer in future.

To wrap up I guess, the data being loaded by the file chooser needs to be global to the applet. For my sketch I included an extra option to set whether it loads or saves (returnVal = fc.showSaveDialog(null);) I'll mention for anyone else trying this that the information you pass to the file chooser function needs to be final. eg:
Code:

fileChooser(final boolean isOpenDialog){
//yadda yadda
}

But it doesn't need to be final outside the function. So the file name filter stuff will just need final tagged in front of it.
Re: How to show a JFileChooser
Reply #11 - Mar 22nd, 2006, 3:10pm
 
trust me, it shouldn't actually work. that's the whole point of the thing running in a separate thread. the fact that it's working is just luck, and on a different machine or different platform or different day, it may stop working.
Re: How to show a JFileChooser
Reply #12 - Mar 27th, 2006, 5:42pm
 
Works fine on every machine at anytime.

Until I export it. Then it only works on PCs.

In your version you assign an image in the other thread, and in mine I assign a String. I get the fact that having a return value is ridiculous, that's something I blatantly overlooked. Is it the fact that the function has a returnable value that means it shouldn't work?

The annoying thing is that this code is all embedded in a project using the AIExport library, which does funny stuff to Processing's "folder" variable. So I'm beyond making concrete examples.
Re: How to show a JFileChooser
Reply #13 - Mar 27th, 2006, 7:04pm
 
exactly.. the whole point is that it has to launch off into another thread, so the code for launching the thread may or may not happen before the function returns the value, that's why i was saying to use a callback (imageChosen() in the code i posted). the callback could pass the filename instead of the image, if that's what you prefer.

sounds like AIExport needs some updating.. why not use the PDF library instead?
Re: How to show a JFileChooser
Reply #14 - Sep 3rd, 2009, 1:50pm
 
Heyo, resurrecting an old one here....

Fry's method works great, in terms of the file chooser coming up without problems and all, but after the chooser goes away I'm not getting keyPressed calls anymore. Any idea why that might be?

I do continue to get mousePressed calls.
Pages: 1 2