Modified JFileChooser

I've browsed through the API and noticed that there are some methods to modify the default JFileChooser (like adding components and such). However, I'm not sure how specific these changes can be and how much control I would have over their placement in the JFileChooser. From what I can gather, I wouldn't have much control.
First question - How much control would I have over customizing the layout using the JFileChooser methods?
So my alternative is to design my own file chooser modeled after the JFileChooser. But I'm not sure where to begin on this or what might be involved in designing such an interface and the methods to back it up with functionality.
Second question - What is a good spot to start learning about designing a UI and implementing the back-end to an emulator for a JFileChooser?

Part of my application involves uploading files to a networked server from a desktop. I've got nearly all of the "business code" done, but I need a UI to get some information from the user (the files to be copied/uploaded and basic information about the file set) and pass it to my "business" objects.
Because a JFileChooser has the ability to both gather the files and have an "accessory", I figure that using one would be a great place to start. I would use the JFileChooser for gathering the files and create an accessory that has multiple JPanels each containing components for entering data about the file set being uploaded. The accessory would also be where I would return any error messages by adding new components. If possible, I also want my JFileChooser to "stick around" and have the entry and file selection components become uneditable/unselectable/unusable and activate another part of the accessory - an uneditable JTextArea that displays status messages generated by the validation and upload code to allow the user to observe the actions of the program.
I only need one view, but I need it to have a lot of components going on, aside from the JFileChooser. It's going to be my entire file copy/upload UI. If it has to do with displaying messages from the upload or validation, it's going to happen inside of the file chooser by adding/removing/hiding/changing components.

Similar Messages

  • JFileChooser and other types of "file" systems

    Good afternoon...
    just wondering how reasonable it would be to modify JFileChooser to work with other types of file systems. such as .zip archives, remote FTPs, etc.
    any ideas where i should start?
    i even want to use this for something that doesn't contain files at all, but the analogy works perfectly.
    Schultz.

    Here's how to view remote files with ftp:
    What does FileSystemView view? http://www.crocodile.org/listok/2/WhatDoesFileSystemViewView.shtml
    Cheers
    Tue

  • Cannot cutomize ALL of JFileChooser - what are the property names?

    Setting the UIManager property JFileChooser.homeFolderToolTipText to some value seems to have no effect on my machine running jdk 1.4.1.
    I am able to customize most of the JFileChooser, for instance changing this property does work JFileChooser.lookInLabelText.
    However, I have not been able to find the correct property names of the following textual contents of JFileChooser:
    1. The column names in a detailed list view (file name, size, modified date, ...)
    2. The text and tooltip of the open button when a folder is selected (which differs from the text shown when a file is selected)
    3. The text and tooltip of the home button
    If anyone knows the way to change these properties I would be very interested in hearing from you.
    Randahl

    Hi
    WinNT4:
    1. The column names in a detailed list view (file name, size, modified date, ...)
    UIManager.put("FileChooser.fileNameHeaderText","NEW NAME");
         UIManager.put("FileChooser.fileSizeHeaderText","NEW SIZE");
         UIManager.put("FileChooser.fileTypeHeaderText","NEW TYPE");
         UIManager.put("FileChooser.fileDateHeaderText","NEW DATE");
         UIManager.put("FileChooser.fileAttrHeaderText","NEW ATTR");
    2. The text and tooltip of the open button when a folder is selected (which differs from the text shown when a file is selected)
    UIManager.put("FileChooser.directoryOpenButtonText","NEW OPEN");
    UIManager.put("FileChooser.directoryOpenButtonToolTipText","NEW OPEN DIR TTT");
    3. The text and tooltip of the home button
    UIManager.put("FileChooser.homeFolderToolTipText","NEW TTT FOR HOME");//does not work, "Desktop"
    JFileChooser fc = new JFileChooser();
    sergey

  • How to make the FileName TextField in JFileChooser uneditable.

    I'm trying NOT to allow the user to edit the filename but yet I also want them to see files in the current directory. Currently I have created an extended BasicFileChooserUI class that allows the user to traverse through any directories and the user may click on a file, but filename that is original set has not been edited. But that doesn't help if I can't restrict the textfield box. The filename textfield box is editable by default and I can't seem to find a way to disable it. Anyone with an answer plz help me. I'd greatly appreciate ur help.
    John

    I just searched the java-api and found nothing useful. So, this would be my way:
    You should search through file .../javax/swing/JFilechooser.java (you have the zipped code for the API (?)) and look for our JTextField name. You can modify the file by adding e.g. a setFieldDisabled() method (or whatever you want) and add the new file to your package. Then you will just use your custom ...yourPackage.JFileChooser (or MyFileChooser), which will be an extension of the swing's one.
    If you think it is unusual or complicated, don't, just try it.
    bye, thanasis

  • How to move some components in JFileChoose interface?

    Hi, there,
    I am implementing a GUI including onw area that will display file contents in some directory, I need to display column names(file name, size, modified), in file name column, I would like to display different icon to show it is a directory or a real file. I use JTable to do it, but i couldn't get icon to display, furthermore, each column width is always the same.
    If I use JFileChooser, i cannot remove the input file name, file filter areas, and other components I don't want.
    Anyboby can give me some idea? Thanks in advance.

    Hi, there,
    I am implementing a GUI including onw area that will display file contents in some directory, I need to display column names(file name, size, modified), in file name column, I would like to display different icon to show it is a directory or a real file. I use JTable to do it, but i couldn't get icon to display, furthermore, each column width is always the same.
    If I use JFileChooser, i cannot remove the input file name, file filter areas, and other components I don't want.
    Anyboby can give me some idea? Thanks in advance.

  • Problem with Tab Key in JFileChooser when Details view is selected.

    Hi all,
    Iam using a JFileChooser in my application.When i click Details option in the JFileChooser the files with the size,Type and modified date are displayed.
    When i am using tab to navigate through the JFileChooser,when the tab enters the area where the files are listed with details,the tab is not comming out of the File List area,instead it is traversing with in the files.How do i come out of the File List area using Tab key.I wanted to make a functionality similar to Windows FileChooser where in if we press Tab it goes to the file list and the next tab focus to Text field and so on.
    Is it possible using JFileChooser??
    Pls Help me,
    Thanks and Regards,
    Ravi

    Hi,
    looking at other threads, I think you will
    have to get the button and modify/remove the tool tip
    as you which.
    this thread might help you, at least the way to get the components in the file
    chooser:
    http://forum.java.sun.com/thread.jsp?forum=57&thread=563002

  • 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();
    }

  • File Extention when using JFileChooser

    I'm using the JFileChooser and a FileFilter with for extensions of .ses, and I can't get it to append .ses to a file name if the user doesn't do it at the time they are in the File choser.
    What I've tried:
    JFileChooser fc = new JFileChooser();
    fc.setFileFilter(new SessionFileFilter());
    int retVal = fc.showSaveDialog(null);
    if(retVal == JFileChooser.APPROVE_OPTION){
         f = fc.getSelectedFile();
    if(!f.getName().endsWith(".ses")){
                   f=new File(f.getName()+".ses");
    ...SessionFileChooser...
    public boolean accept(File f) {
              boolean retval = false;
              int pos = f.getName().indexOf(".");
              if(pos != -1){
                   if(f.getName().substring(pos).equals(".ses")){
                        retval = true;
              return retval;
         public String getDescription() {
              return ".ses";
    ...any help would be appreciated, if you need source that compiles i'll get some worked out...
    to clarify the problem, if you go to save this web page and a dialog appears, you don't have to type .htm, but it automatically adds it before saving, this is what i'm trying to achieve.

    These two classes should do it. Let me know if there are any problems
    You are welcome to use and modify this code, but please don't change the package or take credit for it as your own work
    FileExtensionFilter
    ===============
    package tjacobs.ui.fc;
    import java.io.File;
    import javax.swing.filechooser.FileFilter;
    import java.util.ArrayList;
    import java.util.Collections;
    import java.util.Iterator;
    import java.util.List;
    public class FileExtensionFilter extends FileFilter {
        private ArrayList<String> mExtensionList;
        private String mDesc;
        public FileExtensionFilter (String extension) {
            mExtensionList = new ArrayList<String>(1);
            mExtensionList.add(extension);
        public FileExtensionFilter(List<String> extensions) {
            mExtensionList = new ArrayList();
              mExtensionList.addAll(extensions);
        public FileExtensionFilter(String[] extensions) {
            mExtensionList = new ArrayList();
            for (int i =0; i < extensions.length; i++) {
                mExtensionList.add(extensions);
         public void addExtension(String extension) {
              mExtensionList.add(extension);
         public Iterator<String> getExtensions() {
              Iterator<String> i = Collections.unmodifiableList(mExtensionList).iterator();
              return i;
    public boolean accept(File file) {
         if (file.isDirectory()) {
              return true;
    String name = file.getName();
    int idx = name.indexOf(".");
    String type = "";
    if (idx != -1) {
    type = name.substring(idx + 1);
    type = type.toLowerCase();
    return mExtensionList.contains(type);
    public void setDescription(String desc) {
    mDesc = desc;
    public String getDescription() {
    if (mDesc == null) {
    mDesc = "";
    for (int i = 0; i < mExtensionList.size(); i++) {
    mDesc += (i != 0 ? ", " : "") + "." + mExtensionList.get(0).toString();
    mDesc+= " files";
    return mDesc;
    public String getType () {
    return mExtensionList.get(0).toString();
    public static class HTMLFilter extends FileExtensionFilter {
    public HTMLFilter () {
    super(new String[] {"html", "htm"});
    setDescription("Web Page Files");
    public static class RTFFilter extends FileExtensionFilter {
    public RTFFilter () {
    super("rtf");
    setDescription("Rich Text Format Files");
    public static class TextFilter extends FileExtensionFilter {
    public static final String TYPES[] = new String[] {"txt", "text", "java"};
         public TextFilter () {
    super(TYPES);
    setDescription("Text Files");
    FileChooser
    ==========
    * Created on Jun 22, 2005 by @author Tom Jacobs
    package tjacobs.ui.fc;
    import java.awt.Component;
    import java.io.File;
    import java.util.List;
    import javax.swing.JFileChooser;
    import javax.swing.filechooser.FileFilter;
    import javax.swing.filechooser.FileSystemView;
    public class FileChooser extends JFileChooser {
         public FileChooser(FileExtensionFilter filter) {
              super();
              addChoosableFileFilter(filter);
         public FileChooser(String type) {
              this (new FileExtensionFilter(type));
         public FileChooser(List<String> types) {
              this (new FileExtensionFilter(types));
         public FileChooser(String path, FileExtensionFilter filter) {
              super(path);
              addChoosableFileFilter(filter);
              // TODO Auto-generated constructor stub
         public FileChooser(String path, String type) {
              this(path, new FileExtensionFilter(type));
              // TODO Auto-generated constructor stub
         public FileChooser(String path, List<String> types) {
              this(path, new FileExtensionFilter(types));
              // TODO Auto-generated constructor stub
         public FileChooser(File path, FileExtensionFilter filter) {
              super(path);
              addChoosableFileFilter(filter);
         public FileChooser(File path, String type) {
              this(path, new FileExtensionFilter(type));
              // TODO Auto-generated constructor stub
         public FileChooser(File path, List<String> types) {
              this(path, new FileExtensionFilter(types));
              // TODO Auto-generated constructor stub
         public FileChooser(FileSystemView arg0, FileExtensionFilter filter) {
              super(arg0);
              addChoosableFileFilter(filter);
         public FileChooser(FileSystemView arg0, String type) {
              this(arg0, new FileExtensionFilter(type));
              // TODO Auto-generated constructor stub
         public FileChooser(FileSystemView arg0, List<String> types) {
              this(arg0, new FileExtensionFilter(types));
              // TODO Auto-generated constructor stub
         public FileChooser(File path, FileSystemView arg1, FileExtensionFilter filter) {
              super(path, arg1);
              addChoosableFileFilter(filter);
         public FileChooser(File path, FileSystemView arg1, String type) {
              this(path, arg1, new FileExtensionFilter(type));
                        // TODO Auto-generated constructor stub
         public FileChooser(File path, FileSystemView arg1, List<String> types) {
              this(path, arg1, new FileExtensionFilter(types));
              // TODO Auto-generated constructor stub
         public FileChooser(String path, FileSystemView arg1, FileExtensionFilter filter) {
              super(path, arg1);
              addChoosableFileFilter(filter);
              // TODO Auto-generated constructor stub
         public FileChooser(String path, FileSystemView arg1, String type) {
              this(path, arg1, new FileExtensionFilter(type));
              // TODO Auto-generated constructor stub
         public FileChooser(String path, FileSystemView arg1, List<String> types) {
              this(path, arg1, new FileExtensionFilter(types));
              // TODO Auto-generated constructor stub
         public int showSaveDialog(Component c) {
              int ok = super.showSaveDialog(c);
              if (ok == JFileChooser.APPROVE_OPTION) {
                   FileFilter filter = getFileFilter();
                   if (filter instanceof FileExtensionFilter) {
                        File f = getSelectedFile();
                        if (!filter.accept(f)) {
                             setSelectedFile(new File(f.getAbsolutePath() + "." + ((FileExtensionFilter)filter).getType()));
              return ok;

  • How to setToolTipText for a file in jfilechooser?

    I want to set tooltip text for a file in jfilechooser for getting its detail to user without selecting a file as it is in windows explorer(e.g for file size,date modified).
    Since jfilechooser does not give directly reference to a file without clicking the file.
    As i have found after googling that jfilechooser displays file in JList.
    So here is the code that get file in JFileChooser
    private Component findJList(Component comp) {
        if (comp.getClass() == JList.class) return comp;
        if (comp instanceof Container) {
            Component[] components = ((Container)comp).getComponents();
            for(int i = 0; i < components.length; i++) {
                Component child = findJList(components);
    if (child != null) return child;
    return null;
    where in findJList jFileChooser object is passed
    So i wan't to know is there any way so that the child being a file will be able to show tooltip for displaying file size or file details or any thing about File.
    Please give me any solution.                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                       

    Silly me!
    The simple fact that the URL isn't null, means the file exists. No need to explicitly check it again.
    (Unless I'm missing something here?)

  • Show files information with JFileChooser

    Does anyone know how to use JFileChooser to show files information such as size, type and last modified when mouse moves over the files ?
    This function seems to work well with FileDialog class under XP but does not work with JFileChooser.
    Jay

    Revealing hidden files and getting that error are 2 completely different thing. Even though you can't see hidden files in a finder window doesn't mean they are inaccessible to programs and the OS. They are just hidden from view to the user.

  • Multiple FileFilter in a JFileChooser

    I wanna have a save file dialog with a list of choosableFileFilter that the user can select. Here is my code :
    import java.io.File;
    import javax.swing.filechooser.FileFilter;
    public class ImageFilter extends FileFilter {
        private static String description;
        private static String extension;
        private static String loadOrSave;
        private final static String jpeg = "jpeg";
        private final static String jpg = "jpg";
        private final static String gif = "gif";
        private final static String tiff = "tiff";
        private final static String tif = "tif";
        private final static String png = "png";
        public ImageFilter(String ext,String desc,String type) {
            super();
            extension = ext;
            description = desc;
            loadOrSave = type;
        public boolean accept(File f) {
            if (loadOrSave.equals("load")) { // "load" ==> only accept files with the final extension above
                if (f.isDirectory()) {
                    return true;
                String ext = getExtension(f);
                if (ext != null) {
                    if (ext.equals(tiff) || ext.equals(tif) || ext.equals(gif) ||
                        ext.equals(jpeg) || ext.equals(jpg) || ext.equals(png)) {
                        return true;
                    else return false;
                return false;
            else { // "save" ==> only accept files with extension "extension"
                if (f.isDirectory()) {
                    return true;
                String ext = getExtension(f);
                if (ext != null) {
                    if (ext.equals(extension)) return true;
                    else return false;
                return false;
        // Get the extension of a file.
        public static String getExtension(File f) {
            String ext = null;
            String s = f.getName();
            int i = s.lastIndexOf('.');
            if (i > 0 &&  i < s.length() - 1) {
                ext = s.substring(i+1).toLowerCase();
            return ext;
        //The description of the Image filter
        public String getDescription() {
            if (loadOrSave.equals("load")) return "Images (*.jpg,*.jpeg,*.gif,*.png,*.tiff,*.tif)";
            else return description;
        public static String getSaveExtension() {
            if (loadOrSave.equals("save")) return extension;
            else return null;
    }I then use my class in the following code fragment :
    JFileChooser fc = new JFileChooser(currentdir);
            ImageFilter bmp = new ImageFilter("bmp","Images BMP (*.bmp)","save");
            ImageFilter jpeg = new ImageFilter("jpeg","Images JPEG (*.jpeg)","save");
            ImageFilter jpg = new ImageFilter("jpg","Images JPG (*.jpg)","save");
            ImageFilter png = new ImageFilter("png","Images PNG (*.png)","save");
            ImageFilter wbmp = new ImageFilter("wbmp","Images WBMP (*.wbmp)","save");
            fc.addChoosableFileFilter(bmp);
            fc.addChoosableFileFilter(jpeg);
            fc.addChoosableFileFilter(jpg);
            fc.addChoosableFileFilter(png);
            fc.addChoosableFileFilter(png);
            fc.setAcceptAllFileFilterUsed(false);
            int returnVal = fc.showSaveDialog(fc);The problem is that the choosable FileFilters in the save dialog have the same description : Images WBMP (*.wbmp). I don't understand why. I created different ImageFilters and then add them one by one. So where's the problem ?
    Thx in advance.

    Damned !
    I'm always asking myself if I have to use the static modifier for a class variable.
    I don't really understand the concept of static variables...
    I think static variables belongs to the class and not to the instances of this class.. Am I right ?

  • 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);

  • JFileChooser has a bug in 1.6?

    Hi,
    With JRE 1.5/1.4, I believed when you bring up the JFileChooser dialog and select the "Detail" view, you will get 4 columns: Name, Size, Type, and Modified.
    With 1.5/1.4, there seems to be 2 problems:
    1. You cannot sort the list by clicking on the column header
    2. The timestamp doesn't reflect the timezone.
    With 1.6, you get only 3 columns: Name, Size, Modified. However, the values in the Modified column should by "Type" instead. Is this a bug with the JFileChooser in 1.6? Have others seen the same thing?
    --Chung                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                   

    In java 1.6.0_06 it works fine...

  • JFileChooser and remote filesystems

    I want to add(among local file system) a few remote filesystems to JFileChooser ,
    I implemented FileSytestemVIew(FileSystem) and File(RemoteFile) class.
    At the first glance everything looks ok - i can see local folders and remote root folder(in combo box), when i choose remote root i can see remote folders and files, but when i invoke double click to enter remote folders, exception occurs.
    for some reason JFileChooser sees 'ordinary' File - not my RemoteFile, and it treats it as a file (not folder) and wants to open it (approveSelection fires)
    Probably i did not implemented all the methods that are used ..
    Any ideas ? maybe there are some other ways to explore remote filesystems ?
    package pl.edu.pw.browser;
    import javax.swing.filechooser.FileSystemView;
    import java.io.File;
    import java.io.IOException;
    import pl.edu.pw.fileserver.client.Client;
    import java.util.*;
    import javax.swing.Icon;
    public class FileSystem extends FileSystemView {
    public FileSystem(ArrayList servers) {
    this.servers=servers;
    public File createFileObject(File dir, String filename) {
    System.out.println("createFileObject1");
    if (dir instanceof RemoteFile )
    return new RemoteFile(((RemoteFile)dir).getFtp(),dir.getAbsolutePath(), filename);
    return super.createFileObject(dir,filename);
    public boolean isDrive(File dir)
    if (dir instanceof RemoteFile )
    return false;
    return super.isDrive(dir);
    public boolean isFloppyDrive(File dir)
    if (dir instanceof RemoteFile )
    return false;
    return super.isFloppyDrive(dir);
    public boolean isComputerNode(File dir)
    if (dir instanceof RemoteFile)
    if(servers.contains(dir))
    return true;
    else
    return false;
    return super.isComputerNode(dir);
    public File createFileObject(String path) {
    return null;
    public boolean isFileSystem(File f) {
    System.out.println("isFileSystem");
    if (f instanceof RemoteFile) {
    return false;
    } else
    return super.isFileSystem(f);
    public boolean isFileSystemRoot(File dir)
    System.out.println("isFileSystemRoot");
    if (dir instanceof RemoteFile)
    if(servers.contains(dir))
    return true;
    else
    return false;
    return super.isFileSystemRoot(dir);
    public boolean isRoot(File f) {
    System.out.println("isRoot");
    if (f instanceof RemoteFile )
    if(servers.contains(f))
    return true;
    else
    return false;
    return super.isRoot(f);
    public String getSystemTypeDescription(File f)
    if (f instanceof RemoteFile)
    return f.getName();
    return super.getSystemTypeDescription(f);
    public Icon getSystemIcon(File f)
    return super.getSystemIcon(f);
    public boolean isParent(File folder,
    File file)
    if (folder instanceof RemoteFile && file instanceof RemoteFile )
    System.out.println("isParent("+folder.getAbsolutePath()+")("+file.getAbsolutePath()+")");
    if(file.getParent().equals(folder.getAbsolutePath()))
    System.out.println("is");
    return true;
    else
    return false;
    return super.isParent(folder,file);
    public File getChild(File parent,
    String fileName)
    System.out.println("getChild");
    if (parent instanceof RemoteFile )
    return new RemoteFile(((RemoteFile)parent).getFtp(),parent.getAbsolutePath(),fileName);
    return super.getChild(parent,fileName);
    public File createNewFolder(File containingDir)
    throws IOException {
    System.out.println("createNewFolder");
    if (containingDir instanceof RemoteFile )
    return null;
    return new File(containingDir,"/nowyFolder");
    public String getSystemDisplayName(File f)
    if (f instanceof RemoteFile )
    return f.getName();
    else
    return super.getSystemDisplayName(f);
    public File[] getRoots()
    System.out.println("getRoots");
    File[] files = super.getRoots();
    File[] fileAll = new File[files.length+1];
    int i=0;
    for(i=0;i<files.length;i++)
    fileAll=files[i];
    fileAll[i]=createFileSystemRoot((RemoteFile)servers.get(0));
    return fileAll;
    public boolean isHiddenFile(File f) {
    return f.isHidden();
    public File getParentDirectory(File dir) {
    System.out.println("getParentDirectory");
    if (dir instanceof RemoteFile)
    String p = dir.getParent();
    if(p!=null)
    return new RemoteFile(((RemoteFile)dir).getFtp(),p);
    else
    return null;
    else
    return super.getParentDirectory(dir);
    protected File createFileSystemRoot(File f)
    System.out.println("createFileSystemRoot");
    if (f instanceof RemoteFile)
    return new FileSystemRoot( (RemoteFile) f);
    else
    return super.createFileSystemRoot(f);
    static class FileSystemRoot extends RemoteFile {
    public FileSystemRoot(RemoteFile f) {
    super(f.getFtp(),f.getAbsolutePath());
    public File[] getFiles(File dir, boolean useFileHiding) {
    if (dir instanceof RemoteFile)
    RemoteFile[] files = (RemoteFile[])( (RemoteFile) dir).listFiles();
    return files;
    else
    return dir.listFiles();
    public File getHomeDirectory() {
    return super.getHomeDirectory();
    ArrayList servers = null;
    package pl.edu.pw.browser;
    import java.io.File;
    import java.io.FilenameFilter;
    import java.io.FileFilter;
    import pl.edu.pw.fileserver.client.Client;
    import java.util.*;
    import java.text.*;
    import pl.edu.pw.fileserver.Constants;
    public class RemoteFile extends File {
    final static char PATHDELIMS = '/';
    public final static String absoluteStart = "//";
    public RemoteFile(Client ftp, String parent) {
    super(parent);
    this.ftp = ftp;
    path = parent;
    public RemoteFile(Client ftp, String parent, String name) {
    this(ftp, parent);
    if (path.length()>0 && path.charAt(path.length()-1) == PATHDELIMS)
    path += name;
    else
    path += PATHDELIMS + name;
    public boolean equals(Object obj) {
    if (!checked)
    exists();
    return path.equals(obj.toString());
    public boolean isDirectory() {
    if (!checked)
    exists();
    return isdirectory;
    public boolean isFile() {
    if (!checked)
    exists();
    return isfile;
    public boolean isAbsolute() {
    if (!checked)
    exists();
    return path.length() > 0 && path.startsWith(this.absoluteStart);
    public boolean isHidden() {
    if (!checked)
    exists();
    return ishidden;
    public long lastModified() {
    return modified;
    public long length() {
    return length;
    public String[] list() {
    return list(null);
    public String[] list(FilenameFilter filter) {
    System.out.println("list");
    String[] result = null;
    try{
    ArrayList names = (ArrayList)ftp.dir(this.getAbsolutePath());
    ArrayList files = new ArrayList();
    for(int i=0;i<names.size();i++)
    RemoteFile rf = new RemoteFile(ftp,(String)names.get(i));
    if (filter == null || filter.accept(this,rf.getName()))
    files.add(rf.getName());
    result = new String[files.size()];
    files.toArray(result);
    catch(Exception ex)
    ex.printStackTrace();
    return result;
    public File[] listFiles() {
    FileFilter filter = null;
    return listFiles(filter);
    public File[] listFiles(FileFilter filter) {
    System.out.println("listFiles");
    RemoteFile[] result = null;
    try{
    ArrayList names = (ArrayList)ftp.dir(this.getAbsolutePath());
    ArrayList files = new ArrayList();
    for(int i=0;i<names.size();i++)
    RemoteFile rf = new RemoteFile(ftp,(String)names.get(i));
    rf.exists();
    if (filter == null || filter.accept(rf))
    files.add(rf);
    result = new RemoteFile[files.size()];
    System.out.println("listFiles.size="+files.size());
    files.toArray(result);
    catch(Exception ex)
    ex.printStackTrace();
    return result;
    public String getPath() {
    return path;
    public String getCanonicalPath() {
    return getAbsolutePath();
    public String getAbsolutePath() {
    if (!isAbsolute()) {
    return ftp.pwd();
    return path;
    public String getName() {
    String result=path;
    if(result.charAt(result.length()-1) == this.PATHDELIMS)
    result = result.substring(0,result.length()-1);
    int i = result.lastIndexOf(this.PATHDELIMS);
    if(i!=-1)
    result = result.substring(i+1);
    return result;
    public String getParent() {
    String result=path;
    if(result.charAt(result.length()-1) == this.PATHDELIMS)
    result = result.substring(0,result.length()-1);
    int i = result.lastIndexOf(this.PATHDELIMS);
    if(i<3)
    return null;
    result = result.substring(0,i);
    return result;
    public boolean exists() {
    boolean ok = false;
    try {
    String r = ftp.exists(path);
    if(r != null)
    System.out.println("('"+path+"')header:"+r);
    ok = true;
    StringTokenizer st = new StringTokenizer(r,Constants.HEADER_SEPARATOR);
    String answer = st.nextToken();
    if(answer.equals(Constants.TRUE))
    isfile=true;
    isdirectory=false;
    answer = st.nextToken();
    if(answer.equals(Constants.TRUE))
    canread = true;
    answer = st.nextToken();
    if(answer.equals(Constants.TRUE))
    canwrite = true;
    answer = st.nextToken();
    if(answer.equals(Constants.TRUE))
    ishidden = true;
    answer = st.nextToken();
    length = Long.parseLong(answer);
    if(isfile)
    answer = st.nextToken();
    modified = Long.parseLong(answer);
    checked = true;
    catch (Exception ex) {
    ex.printStackTrace();
    return ok;
    public boolean canRead() {
    return canread;
    public boolean canWrite() {
    return canwrite;
    public int hashCode() {
    return path.hashCode() ^ 098123;
    public boolean mkdir() {
    return false;
    public boolean renameTo(File dest) {
    return false;
    public Client getFtp() {
    return ftp;
    private Client ftp;
    private boolean checked = false;
    private boolean isdirectory = true;
    private boolean isfile = false;
    private boolean ishidden = false;
    private boolean canread = false;
    private boolean canwrite = false;
    private String path;
    private long length = 0;
    private long modified =0;
    java.lang.NullPointerException
         at pl.edu.pw.browser.Browser.openLocalFile(Browser.java:136)
         at pl.edu.pw.browser.component.FileChooser.approveSelection(FileChooser.java:31)
         at javax.swing.plaf.basic.BasicFileChooserUI$DoubleClickListener.mouseClicked(BasicFileChooserUI.java:412)
         at java.awt.AWTEventMulticaster.mouseClicked(AWTEventMulticaster.java:208)
         at java.awt.AWTEventMulticaster.mouseClicked(AWTEventMulticaster.java:207)
         at java.awt.Component.processMouseEvent(Component.java:5137)
         at java.awt.Component.processEvent(Component.java:4931)
         at java.awt.Container.processEvent(Container.java:1566)
         at java.awt.Component.dispatchEventImpl(Component.java:3639)
         at java.awt.Container.dispatchEventImpl(Container.java:1623)
         at java.awt.Component.dispatchEvent(Component.java:3480)
         at java.awt.LightweightDispatcher.retargetMouseEvent(Container.java:3450)
         at java.awt.LightweightDispatcher.processMouseEvent(Container.java:3174)
         at java.awt.LightweightDispatcher.dispatchEvent(Container.java:3095)
         at java.awt.Container.dispatchEventImpl(Container.java:1609)
         at java.awt.Window.dispatchEventImpl(Window.java:1590)
         at java.awt.Component.dispatchEvent(Component.java:3480)
         at java.awt.EventQueue.dispatchEvent(EventQueue.java:450)
         at java.awt.EventDispatchThread.pumpOneEventForHierarchy(EventDispatchThread.java:197)
         at java.awt.EventDispatchThread.pumpEventsForHierarchy(EventDispatchThread.java:150)
         at java.awt.EventDispatchThread.pumpEvents(EventDispatchThread.java:144)
         at java.awt.EventDispatchThread.pumpEvents(EventDispatchThread.java:136)
         at java.awt.EventDispatchThread.run(EventDispatchThread.java:99)

    i solve the problem .
    I did not overwrite File.getConicalFile() , this method is invoked at javax.swing.plaf.basic.BasicFileChooserUI$DoubleClickListener.mouseClicked(BasicFileChooserUI.java:412)
    that is why i recived a new object type File when I was waiting for RemoteFile

  • JFileChooser and date format questions

    I have a JFileChooser that currently works - I set the default directory and allow the user to select a file or enter a file name.
    I have been asked to modify this to prepopulate the file name field on the JFileChooser.
    How do I do that? It is not obvious which method to call to set the filename field.
    Also, the file name needs to be a timestamp "*yyyyMMddHHmmss*.dat"
    I tried creating the timestamp part with the following code, but it does not format as expected.
            String s = "";
            SimpleDateFormat dateFormat = new SimpleDateFormat("yyyyMMddddHHmmss");
            try
                java.util.Date now = new java.util.Date();
                java.util.Date dat = dateFormat.parse( now.toString() );
                s = dat.toString();
            }What is wrong with this?
    Thanks.

    I don't do Swing and this is also not the subforum for Swing questions. It has its own subforum.

Maybe you are looking for