JFileChooser - distinguish APPROVE_OPTION

Hi,
is there a way to decide in JFileChooser whether the button was clicked or if something was entered in the "file name" field with <return> afterwards?
Seems like both are APPROVE_OPTIONs

only thing I can think is to look thru the source for JFileChooser and BasicFileChooserUI... or a subclass of that.
I gave it a quick look, but don't actually see where the file chooser text field get's the approveSelection action added to it. But I don't have the source for the windows L&F, so it's probably in there. So you probably need to loop thru the components in the JFileChooser, find the JTextField (there should be only one, the code below can help) and see what action listeners it has.
JTextField field = (JTextField)findComponent(chooser, JTextField.class);
     public static Component findComponent(Component comp, Class c) {
          if(c.isAssignableFrom(comp.getClass())) {
               return comp;
          if(comp instanceof Container) {
               Component[] comps = ((Container)comp).getComponents();
               for(int i = 0; i < comps.length; i++) {
                    Component tmp = findComponent(comps, c);
                    if(tmp != null) {
                         return tmp;
          return null;

Similar Messages

  • JFileChooser.APPROVE_OPTION from a tabbedPane

    Hello all,
    A simple yet frustrating problem. I need to have certain actions run when the open button on the JFileChooser is clicked. All very simple if the chooser is created as a dialig box with
    int returnVal=fc.showOpenDialog(null);
    if(returnVal == JFileChooser.APPROVE_OPTION)
    etc etc.
    However this will not work for a JFileChooser placed permentantly on a JTabbedPane. Does anyone know how else i can utilise the OPEN button when the fileChooser is not a dialog?
    Any help would be much appreciated.

    Maybe you can get some ideas from this:
    import java.awt.*;
    import java.awt.event.*;
    import java.beans.*;
    import javax.swing.*;
    public class FileChooserTest
        public static void main(String[] args)
            final JFileChooser fileChooser = new JFileChooser(".");
            fileChooser.addActionListener(new ActionListener()
                public void actionPerformed(ActionEvent e)
                    String s = e.toString();
                    int start = s.indexOf("returnValue=");
                    int end = s.substring(start).indexOf(",");
                    String retVal = s.substring(start + 12, start + end);
                    System.out.println("retVal = " + retVal);
                    if(retVal.equals("APPROVE_OPTION"))
                        System.out.println("selectedFile = " + fileChooser.getSelectedFile());
                    else
                        System.out.println("s = " + s);
                    if(s.indexOf("APPROVE_OPTION") != -1)
                        System.out.println("APPROVE_OPTION");
            fileChooser.addPropertyChangeListener(new PropertyChangeListener()
                public void propertyChange(PropertyChangeEvent e)
                    System.out.println(e.getPropertyName());
            JPanel panel = new JPanel();
            panel.add(fileChooser);
            JFrame f = new JFrame();
            f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
            f.getContentPane().add(panel);
            f.pack();
            f.setLocation(200,200);
            f.setVisible(true);
    }

  • Problem with JFileChooser and ImageIcon

    I'm trying to create an ImageIcon object from file selected in JFileChooser. The problem is that jfc.getSelectedFile().getAbsolutePath() returns a string with backslashes and the constructor of ImageIcon requires the string to have slashes. I`ve tried to create it via URL but it doesn't work as well...
    String lastUsedPath;
    URL imageURL;
    JFileChooser fc = new JFileChooser();
    JFrame frame = new JFrame();
    frame.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
    int returnVal = fc.showDialog(frame,title);
    if(returnVal==JFileChooser.APPROVE_OPTION){                    
         lastUsedPath = fc.getSelectedFile().getAbsolutePath();
         imageURL = getClass().getResource(lastUsedPath);     //don't really get this but I copied it from Java Swing Tutorial          
    }else{
         return null;
    int curH, curW;            
    ImageIcon srcIcon = new ImageIcon(imageURL);                              
    curW = srcIcon.getIconWidth();
    curH = srcIcon.getIconHeight();If I use it this way imageURL is set to null.
    If I set the imageURL as 'fc.getSelectedFile().toURL()' the string is eg.: "file:/E:/file.jpg" instead of "E:/file.jpg". After that the ImageIcon is created but width and height return -1.
    If I try to create ImageIcon by 'new ImageIcon(lastUsedPath)' I get a not null object but the width & height of the ImageIcon is -1 as well.
    What do I have to do to be able to create an ImageIcon from file selected in JFileChooser? Why is this so hard and mind blowing?

    It still returns the ImageIcon object with width & height set to -1.
    EDIT:
    Got it finally:
    lastUsedPathForStupidImageIcon = fc.getSelectedFile().getPath();     
    img = ImageIO.read(new File(lastUsedPathForStupidImageIcon));
    curH = img.getHeight(this);
    curW = img.getWidth(this);The key was to use another String variable and hold the path instead of the absolute path
    Edited by: Beholder on Jan 17, 2010 1:35 PM

  • How to close JFileChooser dialog only while using ESC key ?

    Hi All,
    I am using a Frame and from this frame i am calling the JFileChooser via a JButton.
    and using JFileChooser ShowOpenDialog() for open and close .
    while doing ESC operation my Main Frame is getting closed with JFileChooser dialog.
    Can i close only JFileChooser dialog while doing ESCAPE key operation.
    I Have Escape key function in Main Frame file and JFileChooser file( EscKeyEventActionIntialization)
    But while debuging i am not able to catch the esc key action inside EscKeyEventActionIntialization.
    I have attached the code, please suggest me , if i need to do any change .
    * To change this template, choose Tools | Templates
    * and open the template in the editor.
    package MainPackage;
    import javax.swing.filechooser.*;
    import java.awt.event.ActionEvent;
    import java.awt.event.KeyEvent;
    import javax.swing.*;
    public class SourceSettings extends javax.swing.JDialog{
        JDialog dialog;
        private javax.swing.JFileChooser jFileChooser1;
        MainFile  mainFile;
        ImageIcon icon = new ImageIcon(getClass().getResource("/Resource/mchpIcon.GIF"));
        /** Creates new form SourceSetting */
        public SourceSettings(MainFile  pMPFS) {
            dialog = new JDialog();
            dialog.setDefaultCloseOperation(JDialog.DISPOSE_ON_CLOSE);
            mainFile = pMPFS;
            jFileChooser1 = new javax.swing.JFileChooser();
            dialog.add(jFileChooser1);
            EscKeyEventActionIntialization();
            jFileChooser1.setDialogTitle("Browse For Folder");
            jFileChooser1.setFont(new java.awt.Font("Microsoft Sans Serif", 0, 11)); // NOI18N
            jFileChooser1.setName("Browse For Folder"); // NOI18N
        public String getDirctoryPath()
            int retval = jFileChooser1.showOpenDialog(dialog);
            dialog.setVisible(true);
            if(retval  == JFileChooser.APPROVE_OPTION)
                return jFileChooser1.getSelectedFile().getAbsolutePath().toString();
            else
                dialog.setVisible(false);
                dialog.dispose();
                return null;
        public String getParentDirctoryPath()
            return jFileChooser1.getCurrentDirectory().getAbsolutePath().toString();
        public String getOutputDirctoryPath()
            if(jFileChooser1.showOpenDialog(mainMpfs)  == JFileChooser.APPROVE_OPTION)
               return jFileChooser1.getCurrentDirectory().getAbsolutePath().toString();
            else
               dialog.dispose();
               return null;
        private void EscKeyEventActionIntialization()
            Action  ESCactionListener = new AbstractAction () {
              public void actionPerformed(ActionEvent actionEvent) {
                dialog.setVisible(false);
                dialog.dispose();
            KeyStroke stroke = KeyStroke.getKeyStroke(KeyEvent.VK_ESCAPE, 0, true);
            JComponent comp = dialog.getRootPane();
            comp.getInputMap(JComponent.WHEN_IN_FOCUSED_WINDOW).put(stroke, "ESCAPE");
            ActionMap actionMap = comp.getActionMap();
            actionMap.put("ESCAPE", ESCactionListener);
    }

    You have a class that extends JDialog and has a JDialog member variable (very confusing), and no main(...) method. How is the class used as a JDialog?
    To get better help sooner, post a SSCCE that clearly demonstrates your problem. Note that this should be executable and should not contain any extraneous code.
    db

  • Applet with JFilechooser called from a Javascript blocks paint messages

    Hi,
    I am trying to create an applet that can:
    1) be called from a Javascript
    2) displays a file selection dialog for multi-selecting files
    3) returns the selected filenames in a string to the JavaScript
    I am able to use doPrivileged to apply the necessary security context to launch a JFilechooser and return the filenames selected. However, When the JFilechooser dialog is visible and the user moves the dialog window around the HTML pages dose not receive any repaint messages. They seem to be blocked by the thread that launched the JFilechooser dialog and is probably blocking update events as the dialog is still visible.
    I know I need some type of a message pump so the child thread can inform the parent thread and the browser to repaint. However, I don't know how to do this.
    Please help.
    ------Applet Code Begin:-----
    import java.awt.Color;
    import java.awt.Graphics;
    import java.awt.AWTEvent;
    import java.awt.event.AWTEventListener.*;
    import java.awt.event.MouseMotionListener;
    import java.awt.event.MouseEvent;
    import java.io.File;
    import java.util.Locale;
    import java.util.MissingResourceException;
    import java.util.Properties;
    import java.util.ResourceBundle;
    import java.util.Vector;
    import javax.swing.JApplet;
    import javax.swing.JButton;
    import javax.swing.JComponent;
    import javax.swing.JFileChooser;
    import javax.swing.JOptionPane;
    public class SampleApplet extends JApplet
       boolean allowDirs=false;
       boolean allowFiles=true;
       boolean hidden=false;
       File lastUserDir=null;
       public void init()
        public void start()
        public void stop()
        public String selectFiles()
           String choosenFiles = null;
           choosenFiles = new String((String)java.security.AccessController.doPrivileged(
           new java.security.PrivilegedAction()
         public Object run()
            String choosenFiles=new String();
                 JFilechooser fc = new JFilechooser();
         fc.setFileSelectionMode(allowDirs ? (allowFiles ? JFileChooser.FILES_AND_DIRECTORIES
            : JFileChooser.DIRECTORIES_ONLY)
            : JFileChooser.FILES_ONLY);
         fc.setMultiSelectionEnabled(true);
                 int returnVal = fc.showOpenDialog(null);
                 if (returnVal == JFileChooser.APPROVE_OPTION)
                    choosenFiles = "The selected filesnames will be stuffed here";
              return choosenFiles; //return whatever you want
           return choosenFiles;   
    ------Applet Code End:-----
    ------Html Code Begin:-----
    <html>
    <applet id="SampleApplet" archive="SampleApplet.jar"; code="SampleApplet.class"; width="2" height="2" codebase=".">
    </applet>
    <head>
        <title>Untitled Page</title>
    <script language="javascript" type="text/javascript">
    function SelectFiles_onclick()
      var s = (document.applets[0].selectFiles());
      alert(s);
    </script>
    </head>
    <body>
        Click Test button to select files
        <input id="SelectFiles" type="button" value="Select Files" onclick="return SelectFiles_onclick()" />
    </body>
    </html>
    ------Html Code End:-----

    try this:
    first don't open the file dialog in the SelectFiles call. Start a new thread that does that. Then return from the SelectFiles call immediately. Now after the user selectes the files call back into the javascript by doing something like this:
    pass the list of files into this function, each on being a String in the params array
        public synchronized void sendDataToUI(Object[] params) {
            if (FuserState.hasQuit()) {
                return;
            String function = "getUpdates";
            if (logger.isLoggable(Level.FINE)) {
                logger.log(Level.FINE, "Calling Javascript function " + function);
            if (getJavaScriptWindow() == null) {
                logger.log(Level.SEVERE, "Member javascriptWindow is NULL, no call was made!");
                return;
            try {
                getJavaScriptWindow().call(function, params);
            catch (netscape.javascript.JSException x) {
                if (params == null) {
                    logger.log(Level.SEVERE, "p=NULL PARAM");
                } else {
                    logger.log(Level.SEVERE, "p=" + params[0]);
        protected JSObject getJavaScriptWindow() {
            javascriptWindow = JSObject.getWindow(this);
        }

  • Problem with JFileChooser when run using Netbeans

    I just want to state that I have NO problem writing the code that brings up this component. My problem is what happens when the JFileChooser component is loaded. My environment is Windows Vista, Java SE 1.6.0. -> Netbeans IDE 5.0. The code I use is as follows:
    public RegexParser()
    JFileChooser openfile = new JFileChooser();
    openfile.showOpenDialog(RegexParser.this);
    int returnVal = openfile.showOpenDialog(RegexParser.this);
    if (returnVal == JFileChooser.APPROVE_OPTION)
    //This code gets the path of the file and uses as a parameter to parse data.
    filename = openfile.getSelectedFile().getPath();
    openfile.setVisible(false);
    ParseData(filename);
    The problem is when I try to select an option from the combobox labeled "Look In:" Every directory I select which is not the root of the drive will display NO FILES even though there are files in that directory.
    Notice: I have also run the same code using the cmd.exe and it works fine. I have also looked at: http://java.sun.com/docs/books/tutorial/uiswing/components/filechooser.html but have found nothing that has helped me.
    Can someone explain what is the problem? Is this a known bug in Netbeans? Is there any code that can be used as a workaround?

    Yes I copied the code to my machine and run it. The example program had problems when I executed using netbeans it had the problem.
    When I executed using Command Prompt there where no problems.

  • JFileChooser doesn't have focus first time it opens

    Hi!
    I'm using JFileChooser to export some data from JDeveloper to a file. Everything is working file, The only problem I have is, when I run the application and try to export data the choose file dialog opens behind the browser window. This is quite unpleasant since the user thinks the dialog is not opened at all. This only happens the first time when the button to export the data is clicked after the application is run. Every next time the dialog gets the focus and is visible in front of the browser.
    How can I set the focus to dialog the first time it opens?
    My code looks like this:
            UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
            loJFC = new JFileChooser();
            loJFC.setDialogTitle("Export data");
            loJFC.setFileFilter(new TextFilter()); // my class that accepts only txt files
            loJFC.setAcceptAllFileFilterUsed(false);
            loJFC.setSelectedFile(new File("MyFileName.txt")); // set the default name
            int liRetVal = loJFC.showSaveDialog(null);
            if (liRetVal == JFileChooser.APPROVE_OPTION)
              loFile = loJFC.getSelectedFile();
            else
              return;
    // then I write to file etc...Thanks in advance.
    BB

    Hi Frank!
    I have a jspx page in my web application. This jspx includes a commandButton which has above described method as actionListener. So when I click on this button on the jspx the dialog for file selection is opened but hidden the first time it opens.
    Thanks

  • Loading XML Document from JFileChooser

    My initial version of this app I hardcoded the XML filename. Now, I would like to load an xml file via a JFileChooser. The problem I'm having is that I create the DOM Document in the constructor because of dependencies on the JTree. Well, I don't call showDialog until the "open" action is called which is further into the program. By then it's too late. Here is the code. I extracted some unecessary code for reading purposes.
    public class DomGui extends JPanel implements DomGuiConstants, ActionListener
        private JScrollPane treeView;
        private String xmlFilename;
        private Document document;
        private JFileChooser fileChooser;
        private ExtensionFilter fileFilter;
        private static JFrame frame;
        private static JTree jtree;
        public DomGui() throws Exception
            frame = new JFrame(DOM_VIEWER);
            fileChooser = new JFileChooser();
            fileFilter = new ExtensionFilter(XML_EXTENSION, XML_DESCRIPTION);
            // Create the Document
            //xmlFilename = "W:/RoseModel/ImplementationView/seng/ewcs/clwc/Simulation/Utilities/Xml/DomViewer/TVschedule.xml";
            try
                CreateDomDocument createDomDocument = new CreateDomDocument(xmlFilename);
                document = createDomDocument.getDocument();
            catch (FileNotFoundException fnfe)
                System.out.println(fnfe);
                System.exit(1);
            // Create a Tree Model
            DomTreeModel model = new DomTreeModel(document);
            // Create a renderer
            DomTreeCellRenderer  treeCellRenderer = new DomTreeCellRenderer();
            // Create the JTree
            jtree = new JTree(model);
            // Create an Editor
            DomTreeCellEditor treeCellEditor = new DomTreeCellEditor(jtree);
            // Build left-side view
            // an empty tree and put it a JScrollPane so users can see
            // its contents as it gets large
            treeView = new JScrollPane(jtree);
            treeView.getViewport().add(jtree);
            treeView.setPreferredSize(new Dimension( leftWidth, windowHeight ));
            // Create a JSplitPane to hold the left side JTree
            // and the right side JEditorPane
            // Build split-pane view
            splitPane = new JSplitPane( JSplitPane.HORIZONTAL_SPLIT,
                                                       treeView,
                                                       htmlView );
            splitPane.setContinuousLayout( true );
            splitPane.setDividerLocation( leftWidth );
            splitPane.setPreferredSize(new Dimension
                                                        ( windowWidth + 10, windowHeight+10 ));
            // Add GUI components
            this.setLayout(new BorderLayout());
            this.add("Center", splitPane );
        public static void makeFrame()
            int FRAME_WIDTH = 670;
            int FRAME_HEIGHT = 600;
            // Set up the tree, the views, and display it all
            try
                final DomGui guiPanel = new DomGui();
                frame.getContentPane().add("Center", guiPanel );
            catch (Throwable throwable)
                throwable.printStackTrace();
                System.exit(1);
        public void actionPerformed(ActionEvent actionEvent)
            String actionCommand = actionEvent.getActionCommand();
            System.out.println("Action: " + actionCommand);
            if (actionCommand.equalsIgnoreCase("Quit"))
                System.exit(0);
            else if (actionCommand.equalsIgnoreCase("Open"))
                showDialog("Open XML File",
                                 "Open",
                                 "Open the file",
                                 'o',
                                 null);
        // end actionPerformed
        public File showDialog (String dialogTitle,
                                            String approveButtonText,
                                            String approveButtonToolTip,
                                            char approveButtonMnemonic,
                                            File file)
            fileChooser.setDialogTitle(dialogTitle);
            fileChooser.setApproveButtonText(approveButtonText);
            fileChooser.setApproveButtonToolTipText(approveButtonToolTip);
            fileChooser.setApproveButtonMnemonic(approveButtonMnemonic);
            fileChooser.setFileSelectionMode(fileChooser.FILES_ONLY);
            fileChooser.rescanCurrentDirectory();
            fileChooser.setSelectedFile(file);
            fileChooser.addChoosableFileFilter(fileFilter);
            fileChooser.setFileFilter(fileFilter);
            int result = fileChooser.showDialog(this, null);
            System.out.println("Result is: " +result);
            if (result == fileChooser.APPROVE_OPTION)
                System.out.println("I'm Here 1");
                System.out.println("File selected: " + fileChooser.getSelectedFile());
                xmlFilename = fileChooser.getSelectedFile().toString();
                return fileChooser.getSelectedFile();
            else
                System.out.println("I'm Here 2");
                return null;
        // end showDialog
    [\code]                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                           

    In your actionPerformed() method, shouldn't you do something with the File returned by showDialog()? For instance:
            else if (actionCommand.equalsIgnoreCase("Open"))
                xmlFilename = showDialog("Open XML File",
                                 "Open",
                                "Open the file",
                                'o',
                                 null).getName();
            }Because it seems that, for now at least, you're choosing a file and then just kinda throwing it away...

  • How to prevent JFileChooser automatically changing to parent directory?

    When you show only directories, and click on the dir icons to navigate, and then dont select anything and click OK, it automatically 'cd's to the parent folder.
    My application is using the JFileChooser to let the user navigate through folders and certain details of 'foo' files in that folder are displayed in another panel.
    So we dont want the chooser automatically changing dir to parent when OK is clicked. How to prevent this behavior?
    I considered extending the chooser and looked at the Swing source code but it is hard to tell where the change dir is happening.
    thanks,
    Anil
    To demonstrate this, I took the standard JFileChooserDemo from the Sun tutorial and modified it adding these lines
              // NEW line 45 in constructor
              fc.addPropertyChangeListener((PropertyChangeListener) this);
              fc.setFileSelectionMode(JFileChooser.DIRECTORIES_ONLY);
          * NEW -
          * @see java.awt.event.ActionListener#actionPerformed(java.awt.event.ActionEvent)
         public void propertyChange(PropertyChangeEvent e) {
              String prop = e.getPropertyName();
              if (JFileChooser.DIRECTORY_CHANGED_PROPERTY.equals(prop)) {
                   System.out.println("DIRECTORY_CHANGED_PROPERTY");
                   File file = (File) e.getNewValue();
                   System.out.println("DIRECTORY:" + file.getPath());
         }

    Here is the demo:
    package filechooser;
    import java.awt.BorderLayout;
    import java.awt.Insets;
    import java.awt.event.ActionEvent;
    import java.awt.event.ActionListener;
    import java.beans.PropertyChangeEvent;
    import java.beans.PropertyChangeListener;
    import java.io.File;
    import javax.swing.ImageIcon;
    import javax.swing.JButton;
    import javax.swing.JFileChooser;
    import javax.swing.JFrame;
    import javax.swing.JPanel;
    import javax.swing.JScrollPane;
    import javax.swing.JTextArea;
    import javax.swing.SwingUtilities;
    import javax.swing.UIManager;
    * FileChooserDemo.java uses these files:
    *   images/Open16.gif
    *   images/Save16.gif
    public class FileChooserDemo extends JPanel implements ActionListener,
              PropertyChangeListener {
         static private final String newline = "\n";
         JButton openButton, saveButton;
         JTextArea log;
         JFileChooser fc;
         public FileChooserDemo() {
              super(new BorderLayout());
              // Create the log first, because the action listeners
              // need to refer to it.
              log = new JTextArea(5, 20);
              log.setMargin(new Insets(5, 5, 5, 5));
              log.setEditable(false);
              JScrollPane logScrollPane = new JScrollPane(log);
              // Create a file chooser
              fc = new JFileChooser();
              // NEW
              fc.addPropertyChangeListener((PropertyChangeListener) this);
              fc.setFileSelectionMode(JFileChooser.DIRECTORIES_ONLY);
              // Create the open button. We use the image from the JLF
              // Graphics Repository (but we extracted it from the jar).
              openButton = new JButton("Open a File...",
                        createImageIcon("images/Open16.gif"));
              openButton.addActionListener(this);
              // Create the save button. We use the image from the JLF
              // Graphics Repository (but we extracted it from the jar).
              saveButton = new JButton("Save a File...",
                        createImageIcon("images/Save16.gif"));
              saveButton.addActionListener(this);
              // For layout purposes, put the buttons in a separate panel
              JPanel buttonPanel = new JPanel(); // use FlowLayout
              buttonPanel.add(openButton);
              buttonPanel.add(saveButton);
              // Add the buttons and the log to this panel.
              add(buttonPanel, BorderLayout.PAGE_START);
              add(logScrollPane, BorderLayout.CENTER);
          * NEW -
          * @see java.awt.event.ActionListener#actionPerformed(java.awt.event.ActionEvent)
         public void propertyChange(PropertyChangeEvent e) {
              String prop = e.getPropertyName();
              // If the directory changed, don't show an image.
              if (JFileChooser.DIRECTORY_CHANGED_PROPERTY.equals(prop)) {
                   System.out.println("DIRECTORY_CHANGED_PROPERTY");
                   File file = (File) e.getNewValue();
                   System.out.println("DIRECTORY:" + file.getPath());
         public void actionPerformed(ActionEvent e) {
              // Handle open button action.
              if (e.getSource() == openButton) {
                   int returnVal = fc.showOpenDialog(FileChooserDemo.this);
                   if (returnVal == JFileChooser.APPROVE_OPTION) {
                        File file = fc.getSelectedFile();
                        // This is where a real application would open the file.
                        log.append("Opening: " + file.getName() + "." + newline);
                   } else {
                        log.append("Open command cancelled by user." + newline);
                   log.setCaretPosition(log.getDocument().getLength());
                   // Handle save button action.
              } else if (e.getSource() == saveButton) {
                   int returnVal = fc.showSaveDialog(FileChooserDemo.this);
                   if (returnVal == JFileChooser.APPROVE_OPTION) {
                        File file = fc.getSelectedFile();
                        // This is where a real application would save the file.
                        log.append("Saving: " + file.getName() + "." + newline);
                   } else {
                        log.append("Save command cancelled by user." + newline);
                   log.setCaretPosition(log.getDocument().getLength());
         /** Returns an ImageIcon, or null if the path was invalid. */
         protected static ImageIcon createImageIcon(String path) {
              java.net.URL imgURL = FileChooserDemo.class.getResource(path);
              if (imgURL != null) {
                   return new ImageIcon(imgURL);
              } else {
                   System.err.println("Couldn't find file: " + path);
                   return null;
          * Create the GUI and show it. For thread safety, this method should be
          * invoked from the event dispatch thread.
         private static void createAndShowGUI() {
              // Create and set up the window.
              JFrame frame = new JFrame("FileChooserDemo");
              frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
              // Add content to the window.
              frame.add(new FileChooserDemo());
              // Display the window.
              frame.pack();
              frame.setVisible(true);
         public static void main(String[] args) {
              // Schedule a job for the event dispatch thread:
              // creating and showing this application's GUI.
              SwingUtilities.invokeLater(new Runnable() {
                   public void run() {
                        // Turn off metal's use of bold fonts
                        UIManager.put("swing.boldMetal", Boolean.FALSE);
                        createAndShowGUI();
    }

  • How to save a file in Jfilechooser with extension

    hi all
    i'm trying to save a file with a certain extension
    i have my class that extends FileFilter, and which write into the jfilechooser combo box with extensions. .jar
    how can i save a file with this extension?
    here is the code
    JFileChooser fileChooser = new JFileChooser();
              fileChooser.addChoosableFileFilter(new JarFilter());
              int returnVal = fileChooser.showDialog(new JFrame(), "Export");
              if (returnVal == JFileChooser.APPROVE_OPTION) {
                   File file = fileChooser.getSelectedFile();
                   try {
                        JarExporter exporter=new JarExporter(this.generateXMLString(file.getName().replaceAll(".jar", "")),
                                       this.editor.getLinkageCanvas().getSelectedWidgetIDs());
                        exporter.exportJarFile(file);
                   } catch (Exception exception) {
                        System.out.println("Export error.");
              }

    hi all
    i'm trying to save a file with a certain extension
    i have my class that extends FileFilter, and which write into the jfilechooser combo box with extensions. .jar
    how can i save a file with this extension?
    here is the code
    JFileChooser fileChooser = new JFileChooser();
              fileChooser.addChoosableFileFilter(new JarFilter());
              int returnVal = fileChooser.showDialog(new JFrame(), "Export");
              if (returnVal == JFileChooser.APPROVE_OPTION) {
                   File file = fileChooser.getSelectedFile();
                   try {
                        JarExporter exporter=new JarExporter(this.generateXMLString(file.getName().replaceAll(".jar", "")),
                                       this.editor.getLinkageCanvas().getSelectedWidgetIDs());
                        exporter.exportJarFile(file);
                   } catch (Exception exception) {
                        System.out.println("Export error.");
              }

  • JFileChooser - File save as

    Hi,
    I have a method in my application called "export" which exports the JPanel content into a file.
    I used the JFileChooser to let the users choose their desired location for saving the file.
    The problem is unless user explicitly types in the file format, it saves the file with no extension.
    How can I have formats like jpg, png in the File Type drop down menu.
    The code is on a different computer, so dont worry about syntax errors, I just write the important bits:
    JFileChooser jfc = new JFileChooser();
    int answer = jfc.showSaveDialog(this);
    if(answer==jfc.APPROVE_OPTION) {
       try {
          File file = jfc.getSelectedFile();
          ImageIO.write(Graph, "png", file); //Graph is what that needs to be exported 
       } catch () {}any help, highly appreciated, thanks

    TheParthian wrote:
    still got the problem,
    I implemented the FileFilter and its two methods, but what I get in the menu is the string i used in the getDescription method.Yeah, that's what the description is meant for.
    what if i want to include more than one extension?Add more filters.
    Also, even if I choose that as the file type, it still saves it with no extension. Do I need to get the string from the menu and add it
    manually to the end of file name?Yes, of course. (That is, you get the selected filter, determine the appropriate extension and add it, if the user did not explicitly specify an extension.)
    BTW - why did you start a new thread? You could have continued in your old one http://forums.sun.com/thread.jspa?threadID=5334819&messageID=10440802#10440802.

  • JFileChooser throws null pointer exception

    I'm using JFileChooser in my gui class. After I make my selection in the file chooser it sets off a null pointer exception. I'm running windows xp professiona. It was working perfectly fine till recently.
    My code for calling the chooser is:
        JFileChooser chooser = new JFileChooser();
        int returnVal = chooser.showOpenDialog(this);
        if(returnVal == chooser.APPROVE_OPTION){
          //setup the client now with the selected file to send
          client.setFile(chooser.getSelectedFile());
          jLabel5.setText(chooser.getSelectedFile().getName());
        }java.lang.NullPointerException
         at ftpresume.ClientGUI.jButton2_actionPerformed(ClientGUI.java:128)
         at ftpresume.ClientGUI_jButton2_actionAdapter.actionPerformed(ClientGUI.java:174)
         at javax.swing.AbstractButton.fireActionPerformed(AbstractButton.java:1786)
         at javax.swing.AbstractButton$ForwardActionEvents.actionPerformed(AbstractButton.java:1839)
         at javax.swing.DefaultButtonModel.fireActionPerformed(DefaultButtonModel.java:420)
         at javax.swing.DefaultButtonModel.setPressed(DefaultButtonModel.java:258)
         at javax.swing.plaf.basic.BasicButtonListener.mouseReleased(BasicButtonListener.java:245)
         at java.awt.Component.processMouseEvent(Component.java:5100)
         at java.awt.Component.processEvent(Component.java:4897)
         at java.awt.Container.processEvent(Container.java:1569)
         at java.awt.Component.dispatchEventImpl(Component.java:3615)
         at java.awt.Container.dispatchEventImpl(Container.java:1627)
         at java.awt.Component.dispatchEvent(Component.java:3477)
         at java.awt.LightweightDispatcher.retargetMouseEvent(Container.java:3483)
         at java.awt.LightweightDispatcher.processMouseEvent(Container.java:3198)
         at java.awt.LightweightDispatcher.dispatchEvent(Container.java:3128)
         at java.awt.Container.dispatchEventImpl(Container.java:1613)
         at java.awt.Window.dispatchEventImpl(Window.java:1606)
         at java.awt.Component.dispatchEvent(Component.java:3477)
         at java.awt.EventQueue.dispatchEvent(EventQueue.java:456)
         at java.awt.EventDispatchThread.pumpOneEventForHierarchy(EventDispatchThread.java:201)
         at java.awt.EventDispatchThread.pumpEventsForHierarchy(EventDispatchThread.java:151)
         at java.awt.EventDispatchThread.pumpEvents(EventDispatchThread.java:145)
         at java.awt.EventDispatchThread.pumpEvents(EventDispatchThread.java:137)
         at java.awt.EventDispatchThread.run(EventDispatchThread.java:100)

    I took a look at checking to see if the file is valid, exists, is readable and everything else. Looks like the file that's returned if fine. I'm not sure why my program crashes when I setup the file though. Here's my code from the client.setFile(File f);
    public void setFile(File f){
        if(f!=null){
          this.f = f;
          try {
            channel = new FileInputStream(f).getChannel();
            client.setupProgressBar(0,(int)f.length());
          }catch (FileNotFoundException e) {client.showError("FileNotFoundException: " + e);}
          catch(IOException e){client.showError("IOException: " + e);}
      }

  • JFileChooser : Exception occurred during event dispatching

    Hi,
    I'm having problems with sorting in 'Details' view of JFileChooser. I'm getting the following NullPointerException when I try to sort by clicking on the header of the JTable which I get in 'Details' view of a JFileChooser.
    Exception occurred during event dispatching:
    java.lang.NullPointerException
    at java.awt.EventQueue.isDispatchThread(Unknown Source)
    at javax.swing.SwingUtilities.isEventDispatchThread(Unknown Source)
    at javax.swing.JComponent.revalidate(Unknown Source)
    at javax.swing.JTable.resizeAndRepaint(Unknown Source)
    at javax.swing.JTable.sortedTableChanged(Unknown Source)
    at javax.swing.JTable.sorterChanged(Unknown Source)
    at javax.swing.RowSorter.fireRowSorterChanged(Unknown Source)
    at javax.swing.RowSorter.fireRowSorterChanged(Unknown Source)
    at javax.swing.DefaultRowSorter.sort(Unknown Source)
    at sun.swing.FilePane$DetailsTableRowSorter.access$1301(Unknown Source)
    at sun.swing.FilePane$DetailsTableRowSorter$1.call(Unknown Source)
    at sun.swing.FilePane$DetailsTableRowSorter$1.call(Unknown Source)
    at java.util.concurrent.FutureTask$Sync.innerRun(Unknown Source)
    at java.util.concurrent.FutureTask.run(Unknown Source)
    at java.util.concurrent.ThreadPoolExecutor$Worker.runTask(Unknown Source)
    at java.util.concurrent.ThreadPoolExecutor$Worker.run(Unknown Source)
    at sun.awt.shell.Win32ShellFolderManager2$ComInvoker$3.run(Unknown Source)
    at java.lang.Thread.run(Unknown Source)
    Any operation performed in the JFileChooser after this exception will generate the same exception & no action is performed. I'm using Java 1.6.0_24. Strangely, this is happening only in client-server mode. Staand-alone is working fine.
    Please provide some urgent inputs to this problem
    Thanks
    Dilip

    Thanks 4 d reply mKorbel, I'm not creating a TableModel. I'm just creating a JFileChooser as shown below.
    JFileChooser fileChooser = new JFileChooser(location);
    fileChooser.setFileSelectionMode(JFileChooser.FILES_ONLY);
    fileChooser.setMultiSelectionEnabled(false);
    fileChooser.setDialogTitle("Choose File");
    if (fileChooser.showOpenDialog(null) == JFileChooser.APPROVE_OPTION)
    Now, the scenario is to bringup the FileChooser, go to Details view, apply sort on any column. This action creates the mentioned NullPointerException.

  • Problem in OPENING file saved as .bmp(JFilechooser)  in PAINTBRUSH / WIN98

    hello
    Using the JFileChooser I saved the contents of a canvas as " .bmp" file
    now when I try to open this ".bmp" file in the paintbbrush application in windows, I am not able to open.,......
    can anyone pls explain me why ?? how ???
    also the vice- versa is not happening....
    a filed saved in ".bmp" format by the paintbrush is not opened in the java using the JFilechooser ???
    I tried to search the forum but not able to find the solution.....
    am still hunting......
    Kind Rgds
    ASHWIN

    post some code .........the code is as follows.............
    for saving.......
    JFileChooser chooser = new JFileChooser();
    int option = chooser.showSaveDialog(this);
    if( option == JFileChooser.APPROVE_OPTION) {
    path = chooser.getSelectedFile().getAbsolutePath();
    saveFile(path);
    public void saveFile(String path){
    try{
    FileOutputStream ostream = new FileOutputStream(path);
         ObjectOutputStream p = new ObjectOutputStream(ostream);
    p.writeObject(points);
    p.writeObject(drawType);
    catch( Exception e){
    System.err.println(e);
    and for opening.........
    JFileChooser chooser = new JFileChooser();
    int option = chooser.showOpenDialog(this);
    if( option == JFileChooser.APPROVE_OPTION) {
    path=chooser.getSelectedFile().getAbsolutePath();
    openFile(path);
    public void openFile(String path){
    try{
    FileInputStream fstream = new FileInputStream(path);
    ObjectInputStream iii = new ObjectInputStream(fstream);
    points = (Vector)iii.readObject();
    repaint();
    catch(Exception e){
    System.out.println("file not found" + e);
    FOR camickr
    please tell me if you know
    HOW TO SAVE A FILE IN " .bmp" format.... so that it could be opened in
    paintbrush application in WIN 98...
    kind rgds
    ASHWIN...

  • JFileChooser file filter and view does not display Drive letters

    This code displays only files that end in abc.xml, and directories. For example, "helloabc.xml" and directory "world" will display as hello and world, respectively.
    However, I am surprised to find that the drive letters are not displayed at all. eg. C:
    any insights?
    thanks,
    Anil
    import java.io.File;
    import javax.swing.JFileChooser;
    import javax.swing.filechooser.FileFilter;
    import javax.swing.filechooser.FileView;
    public class NoDrive {
         protected static final String ABC_FILE_EXTN = "abc.xml";
         public String selectFile(String function){
              File file = null;
              JFileChooser fc = new JFileChooser();
              fc.setFileFilter(new FileFilter() {
                   public boolean accept(File f) {
                        if (!f.isFile() || f.getName().endsWith(ABC_FILE_EXTN))
                             return true;                    
                        return false;
                   public String getDescription() {
                        return "ABC files";
              fc.setFileView(new FileView() {
                   public String getName(File f) {
                        String name = f.getName();
                        if (f.isFile() && name.endsWith(ABC_FILE_EXTN))
                             return name.substring(0, name.indexOf(ABC_FILE_EXTN));
                        return name;
              int returnVal = fc.showDialog(null, function);
              if (returnVal == JFileChooser.APPROVE_OPTION) {
                   file = fc.getSelectedFile();
                   return file.getName();
              return null;
         public static void main(String[] args) {
              (new NoDrive()).selectFile("Open ABC");
    }

    OK. Here's the correct code:
        fc.setFileView(new FileView() {
          public String getName(File f) {
            String name = f.getName();
            if (f.isFile() && name.endsWith(ABC_FILE_EXTN)){
              return name.substring(0, name.indexOf(ABC_FILE_EXTN));
            else{
              return super.getName(f);
        });

Maybe you are looking for

  • I am trying to connect my Macbook 4.1 Black to my Samsung UE50F6400 using a mini DVI to HDMI adaptor

    I bought the UE50F6400 samrt TV. It has 4 HDMI ports. HDMI 4 is HDMI/DVI, HDMI 3 is normal, HDMI 2 is (ARC) and HDMI 1 is (STB). reading the connection diagram it shows Laptops are to be plugged in to HDMI 4 (HDMI/DVI). But when I plug a HDMI cable i

  • How can you tell your iPhone 5s has been unlocked?

    Is there anyway to tell from the Settings menu on the iPhone or from a menu in iTunes that the phone has been unlocked. My wireless carrier has allowed me to unlock my phone because I will be spending an extended period of time in another country. Le

  • Get the file name into a Odi variable

    Hi, I need to get the file name into odi variable like ..A/ETC/file.txt For eg.the filename file.txt should get store in a variable. Then i want to compare the file name stored in the variable with some other value. Please suggest. Thanks.

  • How to have Web Gallery photos have a Watermark?

    I created Web Galleries in Aperture 2.1. I have in the Presets for Web Exporting selected a PSD Watermark I made. But when viewing the photos on the Web Gallery, the photos do not have the Watermark. I also changed the Presets for Image Export to inc

  • How to translate the context menu of Bex Analyzer?

    Hi.experts: In my BW system,I found that the "drill down in row" and "drill down in column" context menu all wrong description.How can I translate the context menu? Points are waiting for you...thanks in advance. Best regards Martin Xie