Forum Stats

  • 3,750,846 Users
  • 2,250,261 Discussions


How to react on events fired by a JFileChooser?

843804 Member Posts: 45,751
edited Mar 31, 2005 5:25AM in Swing
Hello again.

I hava a FileChooser in my application to load an XML-file and then show its contents in a tab of a JTabbedPane.
When the user chooses a file and then clicks on the open-button of the dialog, I want to check if the file exists. In case of a non-existing file I want to show a modal MessageDialog with a corresponding message. During this time the file dialog must not close and stay open until the user cancels the operation or chooses an existing file.

What do I have to do to achieve this? I think I have to add an actionlistener and override the actionPerformed-method of the open-button. But how? Can you perhaps give me a little code example?


  • 800382
    800382 Member Posts: 7,317
    ok. doesn't the file chooser method you call to get it to show return some value that tells you, when it's closed, that a file was choosen or not? And doesn't it then let you get the File object for the selected file/directory? I believe that the answer to both is yes.
  • 843804
    843804 Member Posts: 45,751

    I know all what you say. But that's not the problem. When I ask for the return value and check if the file exists, the filechooser has already closed. So if the file does not exist the user has to open a new filechooser-instance.

    How can I avoid this by e. g. reacting directly on the open-button-actionperformed event of the filechooser?

  • kloeber
    kloeber Member Posts: 287
    i'm not quite sure why you need to check the existence of a file which the file chooser showed you...
    but anyway, here is what i do to the check the existence of a file if a user wants to do a save:
        fileChooser = new JFileChooser() {
          public void approveSelection() {
            File f = getSelectedFile();
            String fileName = f.toString();
            String ext = "." + ((ExtensionFileFilter)getFileFilter()).getFirstExtension();
            if (!fileName.endsWith(ext)) {
                fileName += ext;
            if (!new File(fileName).exists() ||
                (JOptionPane.showConfirmDialog(this, "<html><center><b>File " + fileName + " exists!<br>Do you want to overwrite it?</b></html>", "Confirm", JOptionPane.YES_NO_OPTION) == JOptionPane.OK_OPTION)) {
    maybe it helps.

  • 843804
    843804 Member Posts: 45,751

    That's exactly what I wanted to know.
    So I just have to override the approveSelection() method.

    I need to do this because the user has also the possibility to type a filename into the textfield. That's what I have to check.

    Thank you very much!
This discussion has been closed.