JFileChooser with WAIT_CURSOR

Hi there,
does anybody know how to show the wait cursor while the JFileChooser is reading large directories and updating its internal file list? How to detect the end of filling the file list in order to set back the cursor?
Many thanks for any help!

Although the filechooser will be significantly faster in 1.4.2
(beta coming soon!), I still agree that a wait cursor is sorely
lacking. We will try to add one in a future release.
I haven't tested it, but you could try something like this:
FileChooserUI ui = fileChooser.getUI();
if (ui instanceof BasicFileChooserUI) {
    fileChooser.addPropertyChangeListener(new PropertyChangeListener() {
     public void propertyChange(PropertyChangeEvent e) {
         String s = e.getPropertyName();
         if (s.equals(JFileChooser.DIRECTORY_CHANGED_PROPERTY)) {
          // Set wait cursor here
    ListModel model = ((BasicFileChooserUI)ui).getModel();
    model.addListDataListener(new ListDataListener() {
     public void contentsChanged(ListDataEvent e) {
         // Clear wait cursor here
     public void intervalAdded(ListDataEvent e) { }
     public void intervalRemoved(ListDataEvent e) { }
}Cheers,
Leif Samuelsson
Java Swing Team
Sun Microsystems, Inc.

Similar Messages

  • 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 with FileSystemView Selecting directory

    Hi,
    I am using JFileChooser and with my own implementation of FileSystemView .
    It is imposable to select a Directory.
    Q1. Do you have any clue about the problem?
    Q2. Is there any way I can add action listener to "Open" button.
    or listen to the events of "Open" button.
    Note:
        fileChooser.setFileSelectionMode(JFileChooser.DIRECTORIES_ONLY);is set.
    Regards,
    Byju

    In the future, Swing questions should be posted to the Swing forum:
    http://forum.java.sun.com/forum.jspa?forumID=57
    If you have to select a directory, not an ordinary file, why not do this first?
    fileChooser.setFileSelectionMode(JFileChooser.DIRECTORIES_ONLY);

  • Opening file using JFileChooser with File filtering

    ok guys I am trying set a file filter object to my file chooser it compile but i have a run time error, the error says:
    Exception in thread "AWT-EventQueue-0" java.land.IllegalArgurmentException: Extension must be non-null and not empty
    at javax.swing.filechooser.FileNameExtensionFilter..........
    I have declared
    JFileChooser jfc = new JFileChooser();
    as a global variable
    and in to my ActionListener, ActionPerform the following:
    ActionListener listener = new ActionListener()
              String selection, file, copy;
         public void actionPerformed(ActionEvent e)
    int tipe =0, size = 16;
         String Stile = " ";
         if (e.getSource() == openItem)
              FileNameExtensionFilter filter = new FileNameExtensionFilter("txt");
    jfc.setFileFilter(filter);
              jfc.showOpenDialog(null);
              try
              File f = jfc.getSelectedFile();
              String file = f.getAbsolutePath();
              File f2 = new File(file);
              BufferedReader in = new BufferedReader(new FileReader(f2));
              String text = "";
    String textl = text;
    while( text != null)
                   text = in.readLine() ;
                   textl = textl + text + "\n";
                   System.out.println(text);
    Can some one please tell me whats wrong? and if possible how to fix it? Thank you guys

    A couple of things might help:
    It's a good idea to post the entire stack trace (even though it may appear a bit long). Specifically it helps to know which line in your code triggered the runtime error. You read the stack trace down from the top and the first line you find belonging to your code is a good place to begin looking hard at.
    Another debugging technique is the SSCCE. The idea with this is that you come up with a really brief example illustrating your problem. (ie it compiles, runs and spits out the runtime error). It can be made brief by getting rid of anything extraneous to the problem. A bare button in a frame which when clicked sets up and displays the file chooser should be enough. I describe this as a debugging technique because in the course of constructing such things I often find I isolate - and therefore can see and fix - an error.
    Anyway, sorry this is so general. Maybe someone will come along with a "missing semicolon in line 3"-type solution but, if not, it may be useful.

  • JFileChooser with directory

    Hi friends, i have to select the path of a directory.
    The function of my button for the file is:
    bq.      Action action1 = new AbstractAction("Sfoglia") { \\      public void actionPerformed(ActionEvent evt) { \\      JPanel p = new JPanel(); \\      JFileChooser c = new JFileChooser(); \\      int app = c.showOpenDialog(p); \\      if(app == JFileChooser.APPROVE_OPTION){ \\      chaos = c.getSelectedFile().getPath(); \\     } \\     } \\     };
    how i can modify this function to get the directory??

    In the future, Swing questions should be posted to the Swing forum:
    http://forum.java.sun.com/forum.jspa?forumID=57
    If you have to select a directory, not an ordinary file, why not do this first?
    fileChooser.setFileSelectionMode(JFileChooser.DIRECTORIES_ONLY);

  • JFileChooser with JavaFX

    The problem is that i could use JFileChooser only into desktop JavaFX application. But I need to use it into web browser.
    Is there any way to select files from web browser app ?
    Or how could i grand permissions for JavaFX applet to open filecooser dialog ?
    My Java version 1.6.0_20
    Ubuntu 10.04 (Lucid)
    FireFox v 3.6.3 (Java(TM) Plug-in 1.6.0_20)

    Or how could i grand permissions for JavaFX applet to open filecooser dialog ?Sign the applet.

  • JFileChooser with Security Manger

    Hello,
    I developed a swing application using JFileChooser. I'll recommend using the security manager and deliver a simple policy. The application works properly. But it throws an exception in XP:
    Exception in thread "Basic L&F File Loading Thread" java.security.AccessControlE
    xception: access denied (java.lang.RuntimePermission modifyThread)
    at java.security.AccessControlContext.checkPermission(Unknown Source)
    at java.security.AccessController.checkPermission(Unknown Source)
    at java.lang.SecurityManager.checkPermission(Unknown Source)
    at java.lang.SecurityManager.checkAccess(Unknown Source)
    at java.lang.Thread.checkAccess(Unknown Source)
    at java.lang.Thread.interrupt(Unknown Source)
    at java.util.concurrent.FutureTask$Sync.innerCancel(Unknown Source)
    at java.util.concurrent.FutureTask.cancel(Unknown Source)
    at sun.awt.shell.Win32ShellFolderManager2$ComInvoker.invoke(Unknown Sour
    ce)
    at javax.swing.plaf.basic.BasicDirectoryModel$LoadFilesThread.run0(Unkno
    wn Source)
    at javax.swing.plaf.basic.BasicDirectoryModel$LoadFilesThread.run(Unknow
    n Source)
    It seems as if the JFileChooser does not really need this permission. So I will recommend to ignore it. Hackers would probably take it as an invitation.
    Is this a bug?
    In a small test project I can see that setting a file filter causes this problem.
    I need a explanation for the users. Why does JFileChooser expect this permission?

    Last week I saw here a bug description I can't find again. It was a similar problem and it was a bug.Oh well that's pretty definitive then.
    I will not do what a stack trace (or malware?) is telling meThat's a pretty strong statement. It rules out debugging your application, for a start!
    and I will not recommend a customer to do it.Another pretty strong statement. You don't really have a choice about that, if it's required to make the application work.
    How dangerous is modifyThread?That's easily answered from the Javadoc:
    'Modification of threads, e.g., via calls to Thread interrupt, stop, suspend, resume, setDaemon, setPriority, setName and setUncaughtExceptionHandler methods. This allows an attacker to modify the behaviour of any thread in the system.'
    Of course it also allows the system and the application to modify the behaviour of any thread in the system. Not granting that permission seems to disable cancelling timer tasks. That seems like a rather too important thing to disable to me. But it's your application.
    users will probably find out that it is not really necessary.If that's true. You haven't actually established that.
    But JFileChooser is probably able to survive without this permission.Again, you're guessing.
    It's clear from the stack trace that the JFileChooser is trying to cancel a task that it has running in a separate thread. If it can't do that, the task will keep running. So without the permission you have a resource leak, a thread leak, and you've lost the ability to cancel timer tasks.

  • Load, crop and saving jpg and gif images with JFileChooser

    Hello!
    I wonder is there someone out there who can help me with a applic that load, (crop) and saving images using JFileChooser with a simple GUI as possible. I'm new to programming and i hope someone can show me.
    Tor

    import java.awt.*;
    import java.awt.event.*;
    import java.awt.image.*;
    import java.io.*;
    import javax.imageio.ImageIO;
    import javax.swing.*;
    import javax.swing.event.*;
    import javax.swing.filechooser.*;
    import javax.swing.filechooser.FileFilter;
    public class ChopShop extends JPanel {
        JFileChooser fileChooser;
        BufferedImage image;
        Rectangle clip = new Rectangle(50,50,150,150);
        boolean showClip = true;
        public ChopShop() {
            fileChooser = new JFileChooser(".");
            fileChooser.setFileFilter(new ImageFilter());
        public void setClip(int x, int y) {
            clip.setLocation(x, y);
            repaint();
        protected void paintComponent(Graphics g) {
            super.paintComponent(g);
            Graphics2D g2 = (Graphics2D)g;
            g2.setRenderingHint(RenderingHints.KEY_ANTIALIASING,
                                RenderingHints.VALUE_ANTIALIAS_ON);
            if(image != null) {
                int x = (getWidth() - image.getWidth())/2;
                int y = (getHeight() - image.getHeight())/2;
                g2.drawImage(image, x, y, this);
            if(showClip) {
                g2.setPaint(Color.red);
                g2.draw(clip);
        public Dimension getPreferredSize() {
            int width = 400;
            int height = 400;
            int margin = 20;
            if(image != null) {
                width = image.getWidth() + 2*margin;
                height = image.getHeight() + 2*margin;
            return new Dimension(width, height);
        private void showOpenDialog() {
            if(fileChooser.showOpenDialog(this) == JFileChooser.APPROVE_OPTION) {
                File file = fileChooser.getSelectedFile();
                try {
                    image = ImageIO.read(file);
                } catch(IOException e) {
                    System.out.println("Read error for " + file.getPath() +
                                       ": " + e.getMessage());
                    image = null;
                revalidate();
                repaint();
        private void showSaveDialog() {
            if(image == null || !showClip)
                return;
            if(fileChooser.showSaveDialog(this) == JFileChooser.APPROVE_OPTION) {
                File file = fileChooser.getSelectedFile();
                String ext = ((ImageFilter)fileChooser.getFileFilter()).getExtension(file);
                // Make sure we have an ImageWriter for this extension.
                if(!canWriteTo(ext)) {
                    System.out.println("Cannot write image to " + ext + " file.");
                    String[] formatNames = ImageIO.getWriterFormatNames();
                    System.out.println("Supported extensions are:");
                    for(int j = 0; j < formatNames.length; j++)
                        System.out.println(formatNames[j]);
                    return;
                // If file exists, warn user, confirm overwrite.
                if(file.exists()) {
                    String message = "<html>" + file.getPath() + " already exists" +
                                     "<br>Do you want to replace it?";
                    int n = JOptionPane.showConfirmDialog(this, message, "Confirm",
                                                          JOptionPane.YES_NO_OPTION);
                    if(n != JOptionPane.YES_OPTION)
                        return;
                // Get the clipped image, if available. This is a subImage
                // of image -> they share the same data. Handle with care.
                BufferedImage clipped = getClippedImage();
                if(clipped == null)
                    return;
                // Copy the clipped image for safety.
                BufferedImage cropped = copy(clipped);
                boolean success = false;
                // Write cropped to the user-selected file.
                try {
                    success = ImageIO.write(cropped, ext, file);
                } catch(IOException e) {
                    System.out.println("Write error for " + file.getPath() +
                                       ": " + e.getMessage());
                System.out.println("writing image to " + file.getPath() +
                                   " was" + (success ? "" : " not") + " successful");
        private boolean canWriteTo(String ext) {
            // Support for writing gif format is new in j2se 1.6
            String[] formatNames = ImageIO.getWriterFormatNames();
            //System.out.printf("writer formats = %s%n",
            //                   java.util.Arrays.toString(formatNames));
            for(int j = 0; j < formatNames.length; j++) {
                if(formatNames[j].equalsIgnoreCase(ext))
                    return true;
            return false;
        private BufferedImage getClippedImage() {
            int w = getWidth();
            int h = getHeight();
            int iw = image.getWidth();
            int ih = image.getHeight();
            // Find origin of centered image.
            int ix = (w - iw)/2;
            int iy = (h - ih)/2;
            // Find clip location relative to image origin.
            int x = clip.x - ix;
            int y = clip.y - iy;
            // clip must be within image bounds to continue.
            if(x < 0 || x + clip.width  > iw || y < 0 || y + clip.height > ih) {
                System.out.println("clip is outside image boundries");
                return null;
            BufferedImage subImage = null;
            try {
                subImage = image.getSubimage(x, y, clip.width, clip.height);
            } catch(RasterFormatException e) {
                System.out.println("RFE: " + e.getMessage());
            // Caution: subImage is not independent from image. Changes
            // to one will affect the other. Copying is recommended.
            return subImage;
        private BufferedImage copy(BufferedImage src) {
            int w = src.getWidth();
            int h = src.getHeight();
            BufferedImage dest = new BufferedImage(w, h, src.getType());
            Graphics2D g2 = dest.createGraphics();
            g2.drawImage(src, 0, 0, this);
            g2.dispose();
            return dest;
        private JPanel getControls() {
            JPanel panel = new JPanel(new GridBagLayout());
            GridBagConstraints gbc = new GridBagConstraints();
            gbc.weightx = 1.0;
            gbc.fill = GridBagConstraints.HORIZONTAL;
            gbc.gridwidth = GridBagConstraints.REMAINDER;
            panel.add(getCropPanel(), gbc);
            panel.add(getImagePanel(), gbc);
            return panel;
        private JPanel getCropPanel() {
            JToggleButton toggle = new JToggleButton("clip", showClip);
            toggle.addActionListener(new ActionListener() {
                public void actionPerformed(ActionEvent e) {
                    showClip = ((AbstractButton)e.getSource()).isSelected();
                    repaint();
            SpinnerNumberModel widthModel = new SpinnerNumberModel(150, 10, 400, 1);
            final JSpinner widthSpinner = new JSpinner(widthModel);
            SpinnerNumberModel heightModel = new SpinnerNumberModel(150, 10, 400, 1);
            final JSpinner heightSpinner = new JSpinner(heightModel);
            ChangeListener cl = new ChangeListener() {
                public void stateChanged(ChangeEvent e) {
                    JSpinner spinner = (JSpinner)e.getSource();
                    int value = ((Number)spinner.getValue()).intValue();
                    if(spinner == widthSpinner)
                        clip.width = value;
                    if(spinner == heightSpinner)
                        clip.height = value;
                    repaint();
            widthSpinner.addChangeListener(cl);
            heightSpinner.addChangeListener(cl);
            JPanel panel = new JPanel(new GridBagLayout());
            GridBagConstraints gbc = new GridBagConstraints();
            gbc.insets = new Insets(2,2,2,2);
            gbc.weightx = 1.0;
            panel.add(toggle, gbc);
            addComponents(new JLabel("width"),  widthSpinner,  panel, gbc);
            addComponents(new JLabel("height"), heightSpinner, panel, gbc);
            return panel;
        private void addComponents(Component c1, Component c2, Container c,
                                   GridBagConstraints gbc) {
            gbc.anchor = GridBagConstraints.EAST;
            c.add(c1, gbc);
            gbc.anchor = GridBagConstraints.WEST;
            c.add(c2, gbc);
        private JPanel getImagePanel() {
            final JButton open = new JButton("open");
            final JButton save = new JButton("save");
            ActionListener al = new ActionListener() {
                public void actionPerformed(ActionEvent e) {
                    JButton button = (JButton)e.getSource();
                    if(button == open)
                        showOpenDialog();
                    if(button == save)
                        showSaveDialog();
            open.addActionListener(al);
            save.addActionListener(al);
            JPanel panel = new JPanel();
            panel.add(open);
            panel.add(save);
            return panel;
        public static void main(String[] args) {
            ChopShop chopShop = new ChopShop();
            ClipMover mover = new ClipMover(chopShop);
            chopShop.addMouseListener(mover);
            chopShop.addMouseMotionListener(mover);
            JFrame f = new JFrame("click inside rectangle to drag");
            f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
            f.getContentPane().add(new JScrollPane(chopShop));
            f.getContentPane().add(chopShop.getControls(), "Last");
            f.pack();
            f.setLocation(200,100);
            f.setVisible(true);
    class ImageFilter extends FileFilter {
        static String GIF = "gif";
        static String JPG = "jpg";
        static String PNG = "png";
        // bmp okay in j2se 1.5+
        public boolean accept(File file) {
            if(file.isDirectory())
                return true;
            String ext = getExtension(file).toLowerCase();
            if(ext.equals(GIF) || ext.equals(JPG) || ext.equals(PNG))
                return true;
            return false;
        public String getDescription() {
            return "gif, jpg, png images";
        public String getExtension(File file) {
            String s = file.getPath();
            int dot = s.lastIndexOf(".");
            return (dot != -1) ? s.substring(dot+1) : "";
    class ClipMover extends MouseInputAdapter {
        ChopShop component;
        Point offset = new Point();
        boolean dragging = false;
        public ClipMover(ChopShop cs) {
            component = cs;
        public void mousePressed(MouseEvent e) {
            Point p = e.getPoint();
            if(component.clip.contains(p)) {
                offset.x = p.x - component.clip.x;
                offset.y = p.y - component.clip.y;
                dragging = true;
        public void mouseReleased(MouseEvent e) {
            dragging = false;
        public void mouseDragged(MouseEvent e) {
            if(dragging) {
                int x = e.getX() - offset.x;
                int y = e.getY() - offset.y;
                component.setClip(x, y);
    }

  • Problam with JFileChooser.

    Hi All,
    I am using JFileChooser with .pdf and .xls extension. when i created new file and do saveAs function it saving properly.(suppose i do temp.pdf). now i am trying to do Save function (suppose i do abc.xls) immediately after SaveAs but its saving file as abc.pdf instade of abc.xls.
    i guss its problam with extension selected while saveAs , any body know how to clear pdf \ xls extension from JFileChooser.
    regards,
    Govind.

    Got the same issue with an iPhone I got today. I have no problem using the earphones and that works alright but no sound comes from the speakers, neither ringtones, lock sound or any of the other sounds.
    I have restored it twice with no luck but I have read about some sort of hardware problem that makes the phone believe that the earphones are plugged in so that might be it. Still haven't found a solution though.

  • How to view BMP images in JFileChooser.. for previewing..

    Friends,
    I was trying to open JFileChooser with preview of BMP images.. but remain unsuccessful.. it was showing JPG and GIF perfectly.. but in case of BMP it does not show anything.. am not using any filter though!!
    how to acheive this!!
    Thanking in advance
    gervini

    camickr.. i think u missed one point..
    The Image I/O system in JAVA 5 has readers and writers for BMP and WBMP formats... so cant I upload BMP image by ImageIO and put them in icons to display... in JFileChooser.. ??
    I want to display just like.. as given at
    http://java.sun.com/docs/books/tutorial/uiswing/components/filechooser.html#advancedexample

  • JFileChooser interpreting zip file as a folder

    I have an app that reads and writes data to zip files. When opening one, I use a JFileChooser with a file filter for zips and directories.
    This works fine except except on XP. If the zip file is on a remote (Novell) file server, the JFileChooser treats the zip file as a directory. You can't open the zip file itself.
    If the client is W2k, there is no problem.
    I'm using JRE 1.4.1.
    Anyone know if there's a tweak to XP to fix this?

    JResourceBrowser is a swing component similar to the javax.swing.JFileChooser but letting the user navigating into a set of directories bound to various protocols or containers. For an usage sample, listing an ftp directory, creating a new file and editing it inside your application. JResourceBrowser is provided by default with a set of "managers" dedicated to ZIP and JAR, FTP and WebDAV.
    http://www.swingall.com/jrb/index.html
    Features :
    * JavaBeans
    * Built with a GridBagLayout
    * Create your own plugins for navigating
    * User Interface delegate for rendering a file
    * Cutomize the set of actions
    * Default actions for creating a new file, deleting, renaming or locking/unlocking
    * Extracting or putting a file content
    * Save/restore the user interface state
    * ZIP, JAR support
    * FTP support
    * WebDAV support
    * JDK 1.4 and 1.5 compatibility

  • Selecting all files from JFilechooser and renaming them??

    dear all
    i am working on a application that selects the jpeg,jpg,jpe files form the jfilechooser with an additonal botton rename which calls the rename method and the selected file is renamed.
    i have been succssful in mselecting one file and renaming it.but the problem is with...
    1) Selection of multiple files and sending their names and parent directories getParent(); is not working with taht....should i use arrays to store that .....but how when i have enabled multiple selection already.
    2)SEcond problem is to refersh the contents of JFileChooser after i have renamed it.iwant that it shopuld be refreshed automatically just after renaming has been done.
    help is always appreciated..
    regards
    s m sharma (trainee s/w/ engg)

    hi everybody
    i have done it myself.......it was not too tough that u didnot responed...anyway thanks..
    regards
    s m sharmna

  • Using JFileChooser in GUI Builder / Matisse

    Would appreciate any help with how to modify the code created by the NetBeans GUI Builder / Matisse to use jFileChooser.
    I've added a Menu item to act as a file Open option, called OpenItem, and the GUI builder has added a listener which points to a method OpenItemActionPerformed:
    private void OpenItemActionPerformed(java.awt.event.ActionEvent evt) {                                        
            // TODO add your handling code here:
    } I have also added a jFileChooser component, named jFileChooser1, but if I try to use it in the OpenItemActionPerformed method I get an error.
    private void OpenItemActionPerformed(java.awt.event.ActionEvent evt) {                                        
           JFileChooser1.  
    }     shows error: "<identifier> expected" (as soon as I get to the dot).
    The variable seems to be defined:
    private void initComponents() {
            jFileChooser1 = new javax.swing.JFileChooser();
    }// Variables declaration - do not modify
    private javax.swing.JFileChooser jFileChooser1;
    // End of variables declaration
    Maybe I have gone about this the wrong way, so any clues as to either how I can get the jFileChooser1 variable to work or any way I can use JFilechooser with GUI Builder created application would be much appreciated.
    Thanx in advance.

    The following example creates a file chooser and displays it as first an open-file dialog and then as a save-file dialog:
        String filename = File.separator+"tmp";
        JFileChooser fc = new JFileChooser(new File(filename));
        // Show open dialog; this method does not return until the dialog is closed
        fc.showOpenDialog(frame);
        File selFile = fc.getSelectedFile();
        // Show save dialog; this method does not return until the dialog is closed
        fc.showSaveDialog(frame);
        selFile = fc.getSelectedFile();Here is a more elaborate example that creates two buttons that create and show file chooser dialogs.
        // This action creates and shows a modal open-file dialog.
        public class OpenFileAction extends AbstractAction {
            JFrame frame;
            JFileChooser chooser;
            OpenFileAction(JFrame frame, JFileChooser chooser) {
                super("Open...");
                this.chooser = chooser;
                this.frame = frame;
            public void actionPerformed(ActionEvent evt) {
                // Show dialog; this method does not return until dialog is closed
                chooser.showOpenDialog(frame);
                // Get the selected file
                File file = chooser.getSelectedFile();
        // This action creates and shows a modal save-file dialog.
        public class SaveFileAction extends AbstractAction {
            JFileChooser chooser;
            JFrame frame;
            SaveFileAction(JFrame frame, JFileChooser chooser) {
                super("Save As...");
                this.chooser = chooser;
                this.frame = frame;
            public void actionPerformed(ActionEvent evt) {
                // Show dialog; this method does not return until dialog is closed
                chooser.showSaveDialog(frame);
                // Get the selected file
                File file = chooser.getSelectedFile();
        };Here's some code that demonstrates the use of the actions:
        JFrame frame = new JFrame();
        // Create a file chooser
        String filename = File.separator+"tmp";
        JFileChooser fc = new JFileChooser(new File(filename));
        // Create the actions
        Action openAction = new OpenFileAction(frame, fc);
        Action saveAction = new SaveFileAction(frame, fc);
        // Create buttons for the actions
        JButton openButton = new JButton(openAction);
        JButton saveButton = new JButton(saveAction);
        // Add the buttons to the frame and show the frame
        frame.getContentPane().add(openButton, BorderLayout.NORTH);
        frame.getContentPane().add(saveButton, BorderLayout.SOUTH);
        frame.pack();
        frame.setVisible(true);

  • How do you add a combo box into a Jfilechooser?

    how do you add a combo box into a Jfilechooser?
    thanks

    See the API For JFileChooser
    public void setAccessory(JComponent newAccessory)Extend a JPanel or Such like, put your Combo Box on it, fiddle around with event handling code for the ComboBox..
    Set an Instance of that as The Accessory for the JFileChooser.
    Look In Your Docs:-
    <JAVA_HOME>/Demo/jfc/SwingSet2/src , unpack SwingSet2.jar if neccessary
    In there is a demo of using A JFileChooser with an accessory Panel, and Source code that is adaptable...

  • JFileChooser.showSaveDialog and Filename field

    I am implementing the actionPerformed method for a "Save As" menu command. In my standard JFileChooser "Save" dialog (showSaveDialog, Metal L&F), I volunteer the current filename (by a previous call to setSelectedFile). The dialog opens just fine. If the user selects a file in the list, the name of the selected file appears in the "File name" textfield as expected. But if the user selects a directory in the list, the name of the directory likewise appears in the "File name" textfield.
    From other programs (including JBuilder4) I am used to having the filename stay put when I select and/or open a directory in a Save Dialog. Is this just the way a JFileChooser save dialog works in the Metal L&F, am I doing something strange, or is there a workaround?
    Thanks very much.
        File tempFile = new File( activePI.getPathname() );
        defaultSaveDir = tempFile.getParentFile();
        JFileChooser chooser = new JFileChooser(defaultSaveDir);
        chooser.setSelectedFile(tempFile);

    Thanks to both of you for the help. I actually came up with the key element of trevorryan1's solution shortly after posting my followup yesterday: consuming any setSelectedFile call when the file argument is a directory. Once this test is in, the counter etc is no longer needed! I consider the JFileChooser's "overwrite the filename textfield" behavior to be a bug, since my !file.isDirectory() override of setSelectedFile shouldn't do anything that setFileSelectionMode(JFileChooser.FILES_ONLY) doesn't already do (FILES_ONLY is the default setting).
    Here is the test class that I posted to the BugParade; I'll post the URL when/if it shows up.
    import java.io.File;
    import javax.swing.JFileChooser;
    class JFileChooserBug
      //Note: comment out the first or second declaration of JFileChooser chooser
      public static void main(String[] args)
        // 1. in a standard JFileChooser save dialog, navigating to another
        // directory will (inappropriately) overwrite the "File name:" textfield.
        // This should not happen when fileSelectionMode = FILES_ONLY (the default).
        JFileChooser chooser = new JFileChooser();
        // 2. in a JFileChooser with a hacked setSelectedFile method, the
        // "File name:" text field is (appropriately) left alone.
        //JFileChooser chooser = new MyJFileChooser();
        //chooser.setFileSelectionMode(JFileChooser.FILES_ONLY);  // = default anyway
        // show the Save dialog with a default file selected
        chooser.setSelectedFile( new File("dummyfile") );
        chooser.showSaveDialog(null);
      public static class MyJFileChooser extends JFileChooser
        //OVERRIDE
        public void setSelectedFile(File file)
          if ( !file.isDirectory() )
            super.setSelectedFile(file);
    }

Maybe you are looking for

  • Log into my facebook through my iphone i get this ALERT: this build is only enable for employees

    I use my facebook on my iphone all the time but just a few hours ago i went to log and and it came up with ALERT: this build is only enabled for emplyees I have tried to the whole deleting it then reinstall it, and even turning off the phone but noti

  • Problem using Form's Last_Record()

    I'm trying to append a record to a detail block (in tabular) on my form, by pushing a "AddSelectedRecord" button. The detail block may or may not have records already before appending. I used the following PL/SQL for the button: Declare BEGIN go_bloc

  • Any tutorials on simple responsive navigation bar?

    I made a simple navigation bar using using lists with 4 links. The problem I'm having is adjusting the navbar for different media like the ipad or desktop where the navbar has to go from display:block (mobile) to display inline horizontally. for a de

  • Loading a js file gives this error: "missing ; before statement .. Line 1"

    After "Clearing Recent History" Cache The Error console shows: Error: missing ; before statement Source File: http://www.dmv-rom.ca/res2/res/js/modaldbox.js Line: 1, Column: 14 Source Code: Date: Mon, 22 Aug 2011 20:05:41 GMT and points to the A in A

  • Denied! Can I find out what I requested?

    I can not find a way to get a copy of the "history" of songs that was requested for download in my iTunes store account. I was downloading several songs for an event and can't figure out where I stopped so I can go back and get the ones I don't have