We help IT Professionals succeed at work.

We've partnered with Certified Experts, Carl Webster and Richard Faulkner, to bring you a podcast all about Citrix Workspace, moving to the cloud, and analytics & intelligence. Episode 2 coming soon!Listen Now

x

Display JOptionPane without JFileChooser disappearing

kassidy2010
kassidy2010 asked
on
Medium Priority
1,982 Views
Last Modified: 2008-02-01
Hi,
  I am using a JFileChooser and I am trying to validate some user input.  When the user clicks a file to save (I am using the showSaveDialog() method) I check to see if the file already exists using the exists() method.  The problem I am having is if I show a JOptionPane to the user telling them that the file already exists the JFileChooser disapears.  I do not want the JFileChooser to disapear I want to display the JOptionPane ontop of the JFileChooser.  I want the JFileChooser to disappear if the user clicks Yes on the JOptionPane.  

Thanks for all your help!
Comment
Watch Question

Top Expert 2006

Commented:
when the user presses yes on jfilechooser it will be disapeared if and only if the selected file exists. i dont thinkk if it is possible to press yes and dont select a nonexistant file ? and for the joptionpane, how does it make the jfilechooser disapeard ? closes it or just unfocuses it

Author

Commented:
Unless I am not using the JFileChooser properly, but when the user clicks save if the file is there or not it writes it to disk.  This is for the save not open.  As soon as you press save on the JFileChooser the GUI is no longer visable.  So when I try to display an OptionPane ontop of the JFileChooser it is not there.  I only see the JOptionPane on the screen.  
Top Expert 2006

Commented:


if(fileChooser.showSaveDialog(this) == JFileChooser.APPROVE_OPTION) {
                  do what you need here
            }
Top Expert 2006

Commented:
ah i understand what you need
if(fileChooser.showSaveDialog(this) == JFileChooser.APPROVE_OPTION) {
           check the file existant
           if it exists
           perform write
}
I made something, but it won't work as You expect, so I'm looking forward if someone else can tell me what's wrong.
import java.awt.*;
import java.awt.event.*;
import java.io.*;
import java.net.*;
import java.util.*;
import javax.swing.*;
import javax.swing.event.*;
import java.text.*;
import javax.accessibility.*;

public class Z extends JFrame implements Runnable, ActionListener {
  JFileChooser jfc = new JFileChooser(".") {
    public void approveSelection() {
      if(getSelectedFile().exists()) {
        JOptionPane.showMessageDialog(this, "Existing file selected, choose other one");
      } else {
        //do the saving
        fireActionPerformed(APPROVE_SELECTION);
        jfc.setVisible(false);
      }
    }
  };
  public void init() {
    jfc.showSaveDialog(null);
    jfc.setVisible(false);
    pack();
    center(this);
  }
  public void actionPerformed(ActionEvent ae) {
    //if(jfc.
  }
  public void run() {
    setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    init();
    setVisible(true);
  }
  public void center(Component c) {
    Dimension dim = Toolkit.getDefaultToolkit().getScreenSize();
    setLocation((dim.width - c.getWidth()) / 2, (dim.height - c.getHeight()) / 2);
  }
  public static void main(String[] args) {
    SwingUtilities.invokeLater(new Z());
  }
}

Not the solution you were looking for? Getting a personalized solution is easy.

Ask the Experts
Top Expert 2006

Commented:
you do not need to extend an anonymous class from JFileChooser and override its approveSelection method
as i told

JFileChooser jfc = new JFileChooser();
if(jfc.showSaveDialog(this) == JFileChooser.APPROVE_OPTION) {
      if(getSelectedFile().exists()) {
        JOptionPane.showMessageDialog(this, "Existing file selected, choose other one");
      }
      else
           write to file
}
>> you do not need to extend an anonymous class from JFileChooser and override its approveSelection method
Yes you do. Otherwise the JFileChooser dialog closes before you can check if the file exits. That is not what the Asker is looking for.

StillUnAware is on the right track.. just make the following change to the approveSelection method of the JFileChooser object

              setVisible(false);  // <---remove  jfc.

Author

Commented:
I will try this code and see if it works.  DeanHorak is correct I am for the JFileChooser dialog to not close before I check if file exists.  So how does the dialog work?  I also noticed (I have not spent to much time on this yet.) that it calls my action performed method 2 times.  I have to debug more but can anyone explain why this would happen?  I am only calling the showSaveDialog() once.

Thanks everyone!!!!!
>>So how does the dialog work?

StillUnAware's code is overriding the approveSelection() method of the JFileOption class. The approveSelection method determines whether or not to send back the JFileChooser.APPROVE_OPTION or not. By overriding it his code can check for the existence of the file and take appropriate action, rather than the default action which is to close the dialog and return with the APPROVE_OPTION.

To use this code, instead of simply coding

JFileChooser jfc = new JFileChooser();
jfc.showSaveDialog();

You would code

JFileChooser jfc = new JFileChooser(".") {
    public void approveSelection() {
      if(getSelectedFile().exists()) {
        JOptionPane.showMessageDialog(this, "Existing file selected, choose other one");
      } else {
        //do the saving
        fireActionPerformed(APPROVE_SELECTION);
        setVisible(false);
      }
    }
  };
jfc.showSaveDialog();

Everything else would be the same,,,,

>>it calls my action performed method 2 times.  I have to debug more but can anyone explain why this would happen?
Not without looking at the code...
Top Expert 2006

Commented:
yeah i was wrong

DeanHorak would you explain what is the meaning of "this" in an inner class (static or not), whether it points to the outer class or inner ?
Top Expert 2006

Commented:
i cant understand the deference between jfc.setVisible(false); with and without jfc
"this" references the instance of the enclosing class. "this" always refers to the local (inner-most) class.

If this is used within a method of an inner class, then it refers to the inner class.

Use of "this" is not valid within a static method.
Top Expert 2006

Commented:
thanks :)
In StillUnAware's original code, the statement
        jfc.setVisible(false);
is being invoked from with the approveSelection() method of the JFileChooser class. The instance of the JFileChooser class is named "jfc", but it is not visible to the method withon JFileChooser.

Therefore, leaving off the "jfc" causes the setVisible(false); method to be executed against the current JFileChooser object instance. This could have also been changed to -        

this.setVisible(false);

since simply calling an object's method implies "this".

Top Expert 2006

Commented:
> The instance of the JFileChooser class is named "jfc", but it is not visible to the method withon JFileChooser
I was able to compile the code without removing jfc, so it is visible within inner class method. am I right ?

in my opinion, jfc.setVisible(false); and this.setVisible(false); both would invoke the same instance's method, as jfc and this are both references to the same instance whithin the approveSelection method. isn't it correct ?

Author

Commented:
ok thanks again everyone.  I will test this out when I get home to make sure it works and then accept the proper response.  

Thanks again!
>>I was able to compile the code without removing jfc
My compiler (JDK 1.5) generates the following error with jfc. prepended...
"Cannot refer to non-final variable jfc inside an inner class defined in a different method"

>>in my opinion, jfc.setVisible(false); and this.setVisible(false); both would invoke the same instance's method, as jfc and this are both references to the same instance whithin the approveSelection method. isn't it correct ?
No. jfc should not be visible from within the approveSelection() method. Why you're not getting a compile error I don't know...

Top Expert 2006

Commented:
that error only occures (at least to me) when I try to create an anonymous class whithin a method, and any variable in that method should be declared as final in order to be referencable. in the example above jfc is declared as a class member and does not violate the law. i have JDK 1.5 too. so whats the problem
The approveSelection() method in the code above is a method of the JFileChooser class, not the Z class. The instance variable jfc is an instance variable within the Z class. There is no anonymous class in the example above...

Can you paste your code here that contains the jfc. variable and compiles cleanly?
Top Expert 2006

Commented:

import java.awt.*;
import java.awt.event.*;
import java.io.*;
import java.net.*;
import java.util.*;
import javax.swing.*;
import javax.swing.event.*;
import java.text.*;
import javax.accessibility.*;

class Z extends JFrame implements Runnable, ActionListener {
    int i; // this integer also does not need to be final
  JFileChooser jfc = new JFileChooser(".") {
    public void approveSelection() {
      if(getSelectedFile().exists()) {
        JOptionPane.showMessageDialog(this, "Existing file selected, choose other one");
      } else {
        //do the saving
        fireActionPerformed(APPROVE_SELECTION);
        jfc.setVisible(false);
        i =1; // i can access this int
      }
    }
  };
  public void init() {
  jfc.addActionListener(this);
    jfc.showSaveDialog(null);
    //jfc.setVisible(false);
   
    pack();
    center(this);
  }
  public void actionPerformed(ActionEvent ae) {
    System.out.println("fs");
  }
  public void run() {
    setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    init();
    setVisible(true);
  }
  public void center(Component c) {
    Dimension dim = Toolkit.getDefaultToolkit().getScreenSize();
    setLocation((dim.width - c.getWidth()) / 2, (dim.height - c.getHeight()) / 2);
  }
  public static void main(String[] args) {
    SwingUtilities.invokeLater(new Z());
  }
}
In my code, I'm declaring jfc within an anonymous class.

                  saveMenuItem.addActionListener(new java.awt.event.ActionListener() {    <<<< here's the anonymous class
                        public void actionPerformed(java.awt.event.ActionEvent e) {
                               JFileChooser jfc = new JFileChooser(".") {
                                        public void approveSelection() {
                                          if(getSelectedFile().exists()) {
                                            JOptionPane.showMessageDialog(this, "Existing file selected, choose other one");
                                          } else {
                                            //do the saving
                                            fireActionPerformed(APPROVE_SELECTION);
                                            setVisible(false);
                                          }
                                        }
                                      };
                              jfc.showSaveDialog(getJContentPane());
                        }
                  });
            }

The difference in the example above is that jfc is defined as a class variable rather than a local variable. Apparently that does make the class variables visible to the inner class methods....

Author

Commented:
Thanks again for all of your help!!!
glad I could help
Access more of Experts Exchange with a free account
Thanks for using Experts Exchange.

Create a free account to continue.

Limited access with a free account allows you to:

  • View three pieces of content (articles, solutions, posts, and videos)
  • Ask the experts questions (counted toward content limit)
  • Customize your dashboard and profile

*This site is protected by reCAPTCHA and the Google Privacy Policy and Terms of Service apply.

OR

Please enter a first name

Please enter a last name

8+ characters (letters, numbers, and a symbol)

By clicking, you agree to the Terms of Use and Privacy Policy.