Prob. w/ JFileChooser in 1.4.x on Win. w/ CDF files

I have an application which deals with files named with a .cdf extension. These files are NOT actually MS Channel Definition Files. With Java 1.1, 1.2, and 1.3, JFileChooser displayed my CDF files as files and allowed them to be choosen. With Java 1.4.0 and 1.4.1 FCS on Windows 2000 (problem doesn't exist on Solaris 8), JFileChooser displays them as empty directories. This prevents them from being selectable to be opened by the application. The problem is easy to reproduce with the FileChooserDemo from the Swing tutorial
http://java.sun.com/docs/books/tutorial/uiswing/components/filechooser.html
Simply download and compile the code. Then create an empty file named test.cdf. Under Java 1.4.0, the file will have to be in a directory other than the current working directory of the application. Under Java 1.4.1 the problem occurs even when the file is in the cwd. java.io.File correctly identifies the file as a file (isFile() == true && isDirectory() == false).
Is this new JFileChooser behavior the intended behavior? If so, how can I customize JFileChooser to restore the previous behavior in my applications? Thanks.
Bernie

The best workaround might be to provide a new FileView object
which delegates to the default one. See example below.
(Sorry for the tardy response.)
Leif Samuelsson
The Swing Team, Java Software
Sun Microsystems, Inc.
import java.io.File;
import javax.swing.*;
import javax.swing.filechooser.*;
import javax.swing.plaf.*;
public class CDF {
    public static void main(String[] args) throws Exception {
     JFileChooser fc = new JFileChooser();
     final FileView fv = ((FileChooserUI)fc.getUI()).getFileView(fc);
     fc.setFileView(new FileView() {
         File plainFile = new File("dummy");
         public String getName(File f) {
          return fv.getName(f);
         public String getDescription(File f) {
          if (f.getName().endsWith(".cdf")) {
              return f.getName();
          } else {
              return fv.getDescription(f);
         public String getTypeDescription(File f) {
          if (f.getName().endsWith(".cdf")) {
              return fv.getTypeDescription(plainFile);
          } else {
              return fv.getTypeDescription(f);
         public Icon getIcon(File f) {
          if (f.getName().endsWith(".cdf")) {
              return fv.getIcon(plainFile);
          } else {
              return fv.getIcon(f);
         public Boolean isTraversable(File f) {
          if (f.getName().endsWith(".cdf")) {
              return Boolean.FALSE;
          } else {
              return fv.isTraversable(f);
     if (fc.showOpenDialog(null) == JFileChooser.APPROVE_OPTION) {
         System.out.println("You selected: " + fc.getSelectedFile());
     System.exit(0);
}

Similar Messages

  • How can I get an extension from a file...in JFileChooser

    I have got a problem here. Here I have a JFileChooser, I want to add in
    a FileFilter, and user could only see some type of file. But as long as I
    try to get the extension....It wont compile, could any one teach me how
    to get the extension of a file in JFILECHOOSER???
    ============================================
    import java.io.*;
    import java.io.File.*;
    import javax.swing.filechooser.FileFilter;
    public class MainFrame extends JFrame implements ActionListener {
    public MainFrame() {.............}
    private boolean chooseFile()
    JFileChooser fileChooser = new JFileChooser();
    fileChooser.setFileSelectionMode( JFileChooser.FILES_ONLY );
    FileChoser filtering = new FileChoser("txt");
    fileChooser.setFileFilter(filtering);
    fileChooser.addChoosableFileFilter(filtering);
    int selection = fileChooser.showOpenDialog( this );
    if ( selection == JFileChooser.CANCEL_OPTION )
    return false;
    if (selection == -1) {
    return false;
    File tmpfile = fileChooser.getSelectedFile();
    filename = tmpfile.toString();
    setTitle( "Smiggin Holes 2010 - " + filename );
    return true;
    static class FileChoser extends javax.swing.filechooser.FileFilter
    String extension;
    String description;
    public FileChoser(String extension, String description){
    this.extension = extension;
    this.extension = description;
    // Accept all directories and all gif, jpg, or tiff files.
    public boolean accept(File f)
    if (f != null)
    if (f.isDirectory())
    return true;
    String ext = getExtension(f); //<<<<<<<<<<<THE PROBLEM IS HERE WHEN I TRY TO GET THE EXTENSION OF THE FILE. IT CANT COMPILE
    System.out.println("aasdfasdf"+ext);
    if ((ext!=null)&&(ext.equals(extension)))
    return true;
    return false;
    // The description of this filter
    public String getDescription() {
    return "Just Text Files";
    ======================================
    Could you tell me what can I do? To get the extension of the file selected by the user?
    And What do I have to change?
    Regards,

    Hi,
    can you post your compile error and the code of getExtension().
    Regards
    Ldinka

  • 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.

  • 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

  • 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

  • JFileChooser : save as default file

    I have a JFileChooser which the user uses to pick an excel file that will be imported and displayed in a JTable. I'm looking for a way for the program to save the user's choice as the default, so that every time the application closes and is reopened, he won't have to re-pick the file (unless he is changing it). i'm already using the java.util.prefs class to save other preferences but it seems it only works for primitive data types and so i can't save a "file" to one of the nodes... is there some other way? or am i missing something in the java.util.prefs class?

    pabs123 wrote:
    Though I had found that in the API, i didn't think it was what i was looking for because the problem still remains, how will this file be saved upon closing of the application? I don't know if this has gone off track and maybe the goal which i'm trying to achieve has become lost to you guys but just in case here it is again:
    i have a JTable which must display file "x". I also have a JFilechooser. I want the user to pick a file through the JFileChooser ONE TIME and have that file become the default "x" file. This way when the app is closed, the computer will remember this file and upon startup will import file "x" every time. if the user decides he no longer wants this file but another instead, he can use the JFileChooser to change file "x". what i'm trying to do is save the user the hassle of opening the exact same file every morning (it's a class list).
    maybe i wasn't too clear before but i really appreciate all the help i'm getting, i realize it's a sort of peculiar problem and that's why i came to seek help here where the best reside... hopefully this clears up any misconceptions and helps me find a solution.You aren't too clear now. You said "How will this file be saved upon closing of the application?" but your subsequent verbiage seemed to be talking rather about how to save the name of the file. We've already been through that. You save the name of the file using the java.util.prefs classes. Not the file itself, just the name of the file.
    Or were you really asking about saving the file? You'd use the ordinary Java I/O classes for that. FileWriter and so on.
    Or was your question about how to do something when the application ends?

  • Problem in JFileChooser

    I have got a problem here. Here I have a JFileChooser, I want to add in
    a FileFilter, and user could only see some type of file. But as long as I
    try to get the extension....It wont compile, could any one teach me how
    to get the extension of a file in JFILECHOOSER???
    ============================================
    import java.io.*;
    import java.io.File.*;
    import javax.swing.filechooser.FileFilter;
    public class MainFrame extends JFrame implements ActionListener {
    public MainFrame() {.............}
    private boolean chooseFile()
    JFileChooser fileChooser = new JFileChooser();
    fileChooser.setFileSelectionMode( JFileChooser.FILES_ONLY );
    FileChoser filtering = new FileChoser("txt");
    fileChooser.setFileFilter(filtering);
    fileChooser.addChoosableFileFilter(filtering);
    int selection = fileChooser.showOpenDialog( this );
    if ( selection == JFileChooser.CANCEL_OPTION )
    return false;
    if (selection == -1) {
    return false;
    File tmpfile = fileChooser.getSelectedFile();
    filename = tmpfile.toString();
    setTitle( "Smiggin Holes 2010 - " + filename );
    return true;
    static class FileChoser extends javax.swing.filechooser.FileFilter
    String extension;
    String description;
    public FileChoser(String extension, String description){
    this.extension = extension;
    this.extension = description;
    // Accept all directories and all gif, jpg, or tiff files.
    public boolean accept(File f)
    if (f != null)
    if (f.isDirectory())
    return true;
    String ext = getExtension(f); //<<<<<<<<<<<THE PROBLEM IS HERE WHEN I TRY TO GET THE EXTENSION OF THE FILE. IT CANT COMPILE
    System.out.println("aasdfasdf"+ext);
    if ((ext!=null)&&(ext.equals(extension)))
    return true;
    return false;
    // The description of this filter
    public String getDescription() {
    return "Just Text Files";
    ======================================
    Could you tell me what can I do? To get the extension of the file selected by the user?
    And What do I have to change?
    Regards,

    Hi !
    in the FileChoser class, the public boolean accept(File f) method can be written like this :
    public boolean accept(File f) {
    if (f.isDirectory || f.getName().endsWith(".txt")) { // you can add other extensions
    return true;
    else {
    return false;

  • 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 set file name in a JFileChooser to be some default String?

    Dear all,
    I am tring to make my JFileChooser more user-friendly, so every time that a JFileChooser show up, I would like to fill the file name with some default String, instead of just leaving them blank.
    Does anybody know how to do this?
    Many Thanks!

    look up the set...() methods of the JFileChooser api docs

  • Huge combo boxes in JFileChooser/JList text truncated in 1.4.0

    Hi there,
    We have an application which works fine on Sun JRE 1.3.1
    Recently we started supporting Sun JRE 1.4.0
    But we have some problems with GUI in Sun JRE 1.4.0
    In the JFileChooser dialog the combo box for Folder name
    and file filter is atleast twice as big as normal in when
    using JRE 1.4.0. This seems to be happening only in some particular
    machines. And if we run the application using JRE 1.3.1, on the machine which has problems with JRE 1.4.0, everything works fine.
    Also we use a JList with a custom cell rendered in the application.
    the cell renderer returns a JLabel component with "monospaced" font set in it. In some machines (same machines which has the JFileChooser problem) the upper half of each item in the JList is truncated. This also works fine is we use JRE 1.3.1 on the same machine.
    Please help me if you have any info on these issues.
    Any pointers to related issues on this forum or bug database is highly appreciated.
    Thanks in adance

    Hehe. Give it more time. Could you explain more about what you mean?
    You have a form with the select combo box in it. The user chooses a value from the combo box. Then submits the form. You want to put the value of the option inside the sql statement right? Not the words displayed by the option, but the item you put in the value section right?
    If so, its rather easy:
    query = "INSERT INTO Table VALUE( comboType, \""+request.getParameter( "text")+"\"); The \" might not be necessary depending on how the value is stored.

  • Adding files from JFileChooser to Jlists

    i have created a JList i am wondering how i can add files to this Jlist using a JFile chooser.
    i need to add the actual file with the path and everything i also need to add the contents of a directory into the jList if selected in the Filechooser.
    i have no problem creating a JFilechooser dialog.
    please help me out.

    Hi,
    I gave an example how to use the filechosser and filefilter [url http://forum.java.sun.com/thread.jsp?forum=57&thread=435432]here.
    I think its also where you got the source code above.
    Compactly and performable:import java.awt.*;
    import java.awt.event.*;
    import java.io.File;
    import javax.swing.*;
    import javax.swing.filechooser.FileFilter;
    class Player2 extends JFrame
         public static final int DELAY = 10;
         JButton playButton;
         private JButton Shuffle;
         private JButton stopButton;
         Timer playTimer;
         private JLabel aMessage;
         private JButton openButton;
         JList playList = null;
         JPanel aPanel;
         JFileChooser theFileChooser = new JFileChooser();
         AudioFileFilter filter = new AudioFileFilter();
         JFrame win = new JFrame("AudioPlayer");
         class playTimerListener extends AbstractAction
              public void actionPerformed(ActionEvent e)
                   //myPlayer.play();
         class OpenFileChooserAction extends AbstractAction
              public void actionPerformed(ActionEvent e)
                   int retVal = theFileChooser.showOpenDialog(aPanel);
                   if (retVal == JFileChooser.APPROVE_OPTION)
                        File[] files = theFileChooser.getSelectedFiles();
                        DefaultListModel model = (DefaultListModel) playList.getModel();
                        model.clear();
                        for (int i = 0; i < files.length; i++)
                             if (files.isDirectory())
                                  String[] filesInDirectory = files[i].list();
                                  for (int ii = 0; ii < filesInDirectory.length; ii++)
                                       File f = new File(files[i].getPath() + "/" + filesInDirectory[ii]);
                                       //to prevent subdirectories to be added to the list
                                       if (f.isFile() && filter.accept(f))
                                            model.addElement(filesInDirectory[ii]);
                             else
                                  if (filter.accept(files[i]))
                                       model.addElement(files[i]);
         class playButtonActionListener extends AbstractAction
              public void actionPerformed(ActionEvent e)
                   System.out.println("Playing...");
                   playTimer.start();
         class stopButtonActionListener extends AbstractAction
              public void actionPerformed(ActionEvent e)
                   System.out.println("Stopped!");
                   playTimer.stop();
         public Player2(String s)
              super(s);
              setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
              playTimer = new Timer(DELAY, new playTimerListener());
              theFileChooser.setFileSelectionMode(JFileChooser.FILES_AND_DIRECTORIES);
              theFileChooser.setMultiSelectionEnabled(true);
              theFileChooser.setFileFilter(filter);
              theFileChooser.setFileHidingEnabled(false);
              makeMyGUI();
              pack();
              show();
         private void makeMyGUI()
              aMessage = new JLabel("Nothing selected yet", JLabel.CENTER);
              JScrollPane listScroll = new JScrollPane(playList = new JList(new DefaultListModel()));
              listScroll.setPreferredSize(new Dimension(200, 200));
              playList.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
              playButton = new JButton(new playButtonActionListener());
              playButton.setText("play...");
              stopButton = new JButton(new stopButtonActionListener());
              stopButton.setText("stop...");
              openButton = new JButton(new OpenFileChooserAction());
              openButton.setText("Open...");
              openButton.setBackground(Color.yellow);
              Shuffle = new JButton("Shuffle");
              aPanel = new JPanel();
              aPanel.setBackground(Color.blue);
              aPanel.add(openButton);
              aPanel.add(playButton);
              aPanel.add(stopButton);
              getContentPane().add(listScroll, "Center");
              getContentPane().add(aPanel, "North");
              getContentPane().add(aMessage, "South");
         class AudioFileFilter extends FileFilter
              public boolean accept(File f)
                   if (f.isDirectory())
                        return true;
                   String extension = Utils.getExtension(f);
                   if (extension != null)
                        if (extension.equals(Utils.wav)
                             || extension.equals(Utils.aif)
                             || extension.equals(Utils.rmf)
                             || extension.equals(Utils.au)
                             || extension.equals(Utils.mid))
                             return true;
                        else
                             return false;
                   return false;
              public String getDescription()
                   return "wav, aif, rmf, au and mid";
         public static void main(String[] args)
              try
                   UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
              catch (Exception e)
                   e.printStackTrace();
              new Player2("MP3 PLAYER");
    class Utils
         public final static String wav = "wav";
         public final static String aif = "aif";
         public final static String rmf = "rmf";
         public final static String au = "au";
         public final static String mid = "mid";
         * 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;
    //without formatting
    import java.awt.*;
    import java.awt.event.*;
    import java.io.File;
    import javax.swing.*;
    import javax.swing.filechooser.FileFilter;
    class Player2 extends JFrame
         public static final int DELAY = 10;
         JButton playButton;
         private JButton Shuffle;
         private JButton stopButton;
         Timer playTimer;
         private JLabel aMessage;
         private JButton openButton;
         JList playList = null;
         JPanel aPanel;
         JFileChooser theFileChooser = new JFileChooser();
         AudioFileFilter filter = new AudioFileFilter();
         JFrame win = new JFrame("AudioPlayer");
         class playTimerListener extends AbstractAction
              public void actionPerformed(ActionEvent e)
                   //myPlayer.play();
         class OpenFileChooserAction extends AbstractAction
              public void actionPerformed(ActionEvent e)
                   int retVal = theFileChooser.showOpenDialog(aPanel);
                   if (retVal == JFileChooser.APPROVE_OPTION)
                        File[] files = theFileChooser.getSelectedFiles();
                        DefaultListModel model = (DefaultListModel) playList.getModel();
                        model.clear();
                        for (int i = 0; i < files.length; i++)
                             if (files[i].isDirectory())
                                  String[] filesInDirectory = files[i].list();
                                  for (int ii = 0; ii < filesInDirectory.length; ii++)
                                       File f = new File(files[i].getPath() + "/" + filesInDirectory[ii]);
                                       //to prevent subdirectories to be added to the list
                                       if (f.isFile() && filter.accept(f))
                                            model.addElement(filesInDirectory[ii]);
                             else
                                  if (filter.accept(files[i]))
                                       model.addElement(files[i]);
         class playButtonActionListener extends AbstractAction
              public void actionPerformed(ActionEvent e)
                   System.out.println("Playing...");
                   playTimer.start();
         class stopButtonActionListener extends AbstractAction
              public void actionPerformed(ActionEvent e)
                   System.out.println("Stopped!");
                   playTimer.stop();
         public Player2(String s)
              super(s);
              setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
              playTimer = new Timer(DELAY, new playTimerListener());
              theFileChooser.setFileSelectionMode(JFileChooser.FILES_AND_DIRECTORIES);
              theFileChooser.setMultiSelectionEnabled(true);
              theFileChooser.setFileFilter(filter);
              theFileChooser.setFileHidingEnabled(false);
              makeMyGUI();
              pack();
              show();
         private void makeMyGUI()
              aMessage = new JLabel("Nothing selected yet", JLabel.CENTER);
              JScrollPane listScroll = new JScrollPane(playList = new JList(new DefaultListModel()));
              listScroll.setPreferredSize(new Dimension(200, 200));
              playList.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
              playButton = new JButton(new playButtonActionListener());
              playButton.setText("play...");
              stopButton = new JButton(new stopButtonActionListener());
              stopButton.setText("stop...");
              openButton = new JButton(new OpenFileChooserAction());
              openButton.setText("Open...");
              openButton.setBackground(Color.yellow);
              Shuffle = new JButton("Shuffle");
              aPanel = new JPanel();
              aPanel.setBackground(Color.blue);
              aPanel.add(openButton);
              aPanel.add(playButton);
              aPanel.add(stopButton);
              getContentPane().add(listScroll, "Center");
              getContentPane().add(aPanel, "North");
              getContentPane().add(aMessage, "South");
         class AudioFileFilter extends FileFilter
              public boolean accept(File f)
                   if (f.isDirectory())
                        return true;
                   String extension = Utils.getExtension(f);
                   if (extension != null)
                        if (extension.equals(Utils.wav)
                             || extension.equals(Utils.aif)
                             || extension.equals(Utils.rmf)
                             || extension.equals(Utils.au)
                             || extension.equals(Utils.mid))
                             return true;
                        else
                             return false;
                   return false;
              public String getDescription()
                   return "wav, aif, rmf, au and mid";
         public static void main(String[] args)
              try
                   UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
              catch (Exception e)
                   e.printStackTrace();
              new Player2("MP3 PLAYER");
    class Utils
         public final static String wav = "wav";
         public final static String aif = "aif";
         public final static String rmf = "rmf";
         public final static String au = "au";
         public final static String mid = "mid";
         * 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;
    //Tim

  • How to drag and drop files between two JFileChooser

    Sir i want to drag and drop files between two JFileChooser i don't know how to do that. So is there any reference code for that so that i can able to do it. I have enabled setDragEnabled(true) for both the jfilechooser now i don't now how to drop files in them means drag file from one jfilechooser and drop it to another JFileChooser,.
    Plz help me this is the requirement in my project.

    Note: This thread was originally posted in the [New To Java|http://forums.sun.com/forum.jspa?forumID=54] forum, but moved to this forum for closer topic alignment.

  • JFileChooser - setSelectedFile doesn't work

    Hi,
    I'm using J2SE 1.4.1_01
    I want a suggested name to appear in the "File name" box when I use JFileChooser to save a file. I seem to remember this working fine with Java 1.3. I've seen it mentioned that I can use setText() on this, but don't understand how this can work. I've also tried explicitly setting the file as commented in my code
    This is my code....
    final JFileChooser fc = new JFileChooser();
    File outFile = new File("D:/EVA/Recombination/RATData/" + testSequence + ".csv");
    File dir = new File ("D:/EVA/Recombination/RATData");
    fc.setCurrentDirectory(dir);
    int returnVal = fc.showSaveDialog(null);
    if (returnVal == JFileChooser.APPROVE_OPTION)
    fc.setSelectedFile(outFile);
    /*also tried...
    fc.setSelectedFile(new File "D:/EVA/Recombination/RATData"+testSequence + ".csv"))*/
    try
    PrintWriter writ = new PrintWriter(new FileWriter(outFile));
    etc, etc.......
    Any suggestions?
    Cheers

    Thanks. It now works I had to change the PrintWriter to a BufferedWriter for it to work. I've posted working code below
    final JFileChooser fc = new JFileChooser();
    fc.addChoosableFileFilter(new FileFilterExt("Excel", new String[]{".csv"}));
    File outFile = new File(testSequence + ".csv");
    File dir = new File("D:/EVA/Recombination/RATData");
    fc.setCurrentDirectory(dir);
    fc.setSelectedFile(outFile);
    int returnVal = fc.showSaveDialog(null);
    if (returnVal == JFileChooser.APPROVE_OPTION)
    try
    String filename = fc.getSelectedFile().getAbsolutePath();
    BufferedWriter bw = new BufferedWriter(new FileWriter(filename));
    bw.write("whatever you want to write");// I'm writting from a Vector here, so this line is in a for loop.
    bw.flush();
    bw.close();
    catch (IOException e)
    System.out.print(e);
    Thanks for your help. My award will be made forwith.
    Cheers!

  • JFileChooser, multiple dialogs.

    My JFileChooser is getting the path and filename for a file, to be later opened. I'm placing the path and name in a JTextField.
    My problem is this: whenever I click 'Find' and select my file and click 'Open', the path and filename show in the JTextField, but the dialog reopens as though I'm pressing the 'Find' button again.
    Here's my source:
    import java.awt.*;
    import java.awt.event.*;
    import java.io.*;
    import javax.swing.*;
    import javax.swing.border.*;
    import javax.swing.filechooser.*;
    public class mm5 extends JFrame implements ActionListener
         String[] sItems = new String[1]; // Stores item titles loaded from file. Will be displayed in JList: lstItems
         String[] sProgram = new String[1]; // The program that is ran when the script is executed.
         String[] sLocation = new String[1]; // The location the program tries to open when the script is executed.
         int[] iTimer = new int[1]; // A value of zero will tell the program that this is a schedule-based item instead of a timer-based one.
         int[][] iTimeDef = new int[1][1]; // The first field in this matrix contains the number of scheduled times the item will be called. The second field contains the hour in which the item will be called.
         Border border1 = new EtchedBorder(EtchedBorder.RAISED, Color.black, new Color(165, 163, 151));
         JFrame fraAdminPanel = new JFrame("Admin Panel");
         JFrame fraAddItem = new JFrame("Add Item");
         JPanel panBack = new JPanel();
              JList lstItems = new JList();
              JScrollPane scpItems = new JScrollPane(lstItems);
              JButton btnRun = new JButton("Run");
              JButton btnReport = new JButton("Report");
              JButton btnInfo = new JButton("Info");
              JButton btnHelp = new JButton("Help");
              JButton btnAdmin = new JButton("Admin");
              JButton btnExit = new JButton("Exit");
              JLabel lblTime1 = new JLabel("Time");
              JLabel lblTime2 = new JLabel("00:00");
         JPanel panAdmin = new JPanel();
              JButton btnAddNew = new JButton("Add New");
         JPanel panAddItem = new JPanel();
              JLabel lblItem = new JLabel("Item Title/Desc.");
              JTextField txfItem = new JTextField(100);
              JLabel lblProgram = new JLabel("Program");
              JComboBox cbxProgram = new JComboBox();
              JLabel lblLocation = new JLabel("Location/URL");
              JTextField txfLocation = new JTextField(100);
              JFileChooser fcLocation = new JFileChooser();
              JButton btnLocation = new JButton("Find");
              ButtonGroup btgTimer = new ButtonGroup();
                   JRadioButton optTimer = new JRadioButton("Timer");
                   JRadioButton optTimeDef = new JRadioButton("Scheduled");
                   JRadioButton optNull = new JRadioButton("");
              JLabel lblTimer = new JLabel("Minutes");
              JTextField txfTimer = new JTextField(3);
              JLabel lblTimeDef = new JLabel("Schedule");
              JTextField txfTimeDef = new JTextField(3);
              JButton btnTimeDef = new JButton("Set");
              JCheckBox cbxException = new JCheckBox();
              JButton btnAdd = new JButton("Add Item");
              JButton btnCancel = new JButton("Cancel");
         public mm5()
              try
                   mmInit();
              catch(Exception e)
                   e.printStackTrace();
         } // End of mm5()
         public void actionPerformed(ActionEvent AE)
              String sTheAction = AE.getActionCommand();
              if(sTheAction == "Admin")
                   System.out.println("Admin button pressed.");
                   adminPanel();
              else if(sTheAction == "Add New")
                   System.out.println("Add New button pressed.");
                   addNewInit();
              else if(sTheAction == "Find")
                   System.out.println("Find button pressed.");
                   findFile();
         } // End of actionPerformed()
         public static void main(String[] args)
              mm5 f = new mm5();
         } // End of main()
         public void mmInit()
              this.setTitle("MultiMonitor 5.0.1");
              this.getContentPane().setLayout(null);
              centerWindow(700, 500); // Centers the window and sets the x,y size.
              addWindowListener(
                   new WindowAdapter()
                        public void windowClosing(WindowEvent e)
                             System.exit(0);
              panBack.setLayout(null);
              panBack.setBounds(new Rectangle(5,5,695,495));
              BackLstItemsInit();
              panBack.add(scpItems, null);
              BackBtnInit();
              panBack.add(btnRun, null);
              panBack.add(btnReport, null);
              panBack.add(btnInfo, null);
              panBack.add(btnHelp, null);
              panBack.add(btnAdmin, null);
              panBack.add(btnExit, null);
              this.getContentPane().add(panBack);
              this.setVisible(true);
         } // End of mmInit()
         public void BackLstItemsInit()
              boolean EOF = false;
              scpItems.setBounds(new Rectangle(5,5,575,450));
              scpItems.setBorder(border1);
              scpItems.setVerticalScrollBarPolicy(JScrollPane.VERTICAL_SCROLLBAR_ALWAYS);
              lstItems.setListData(sItems);
         } // End of BackLstItemsInit()
         public void BackBtnInit()
              btnRun.setBounds(new Rectangle(585,5,100,25));
                   btnRun.setActionCommand("Run");
                   btnRun.addActionListener(this);
              btnReport.setBounds(new Rectangle(585,30,100,25));
                   btnReport.setActionCommand("Report");
                   btnReport.addActionListener(this);
              btnInfo.setBounds(new Rectangle(585,55,100,25));
                   btnInfo.setActionCommand("Info");
                   btnInfo.addActionListener(this);
              btnHelp.setBounds(new Rectangle(585,80,100,25));
                   btnHelp.setActionCommand("Help");
                   btnHelp.addActionListener(this);
              btnAdmin.setBounds(new Rectangle(585,105,100,25));
                   btnAdmin.setActionCommand("Admin");
                   btnAdmin.addActionListener(this);
              btnExit.setBounds(new Rectangle(585,130,100,25));
                   btnExit.setActionCommand("Exit");
                   btnAdmin.addActionListener(this);
         } // End of BackBtnInit()
         public void centerWindow(int windowWidth, int windowHeight)
              Dimension d = Toolkit.getDefaultToolkit().getScreenSize();
              this.setBounds((d.width - windowWidth)/2, (d.height - windowHeight)/2, windowWidth, windowHeight);
         } // End of centerWindow()
         public String[] enlargeArray(String[] currentArray)
              String[] newArray = new String[currentArray.length + 1];
              for(int i = 0; i<currentArray.length; i++)
                   newArray[i] = currentArray;
              return newArray;
         } // End of enlargeArray()
         public void adminPanel()
              System.out.println("adminPanel() started");
              fraAdminPanel.setVisible(true);
              fraAdminPanel.getContentPane().add(panAdmin);
              fraAdminPanel.setBounds(50,50,100,200);
              panAdmin.setLayout(null);
              panAdmin.setBounds(0,0,110,200);
              btnAddNew.setBounds(new Rectangle(5,5,100,25));
                   btnAddNew.setActionCommand("Add New");
                   btnAddNew.addActionListener(this);
                   panAdmin.add(btnAddNew, null);
         } // End of adminPanel()
         public void addNewInit()
              System.out.println("addItem() started");
              fraAddItem.setVisible(true);
              fraAddItem.getContentPane().add(panAddItem);
              fraAddItem.setBounds(50,50,325,250);
              panAddItem.setLayout(null);
                   panAddItem.setBounds(0,0,325,250);
              lblItem.setBounds(new Rectangle(5,5,200,25));
                   panAddItem.add(lblItem, null);
              txfItem.setBounds(new Rectangle(5,35,200,25));
                   panAddItem.add(txfItem, null);
              lblProgram.setBounds(new Rectangle(210,5,100,25));
                   panAddItem.add(lblProgram, null);
              cbxProgram.setBounds(new Rectangle(210,35,100,25));
                   panAddItem.add(cbxProgram, null);
              lblLocation.setBounds(new Rectangle(5,65,200,25));
                   panAddItem.add(lblLocation, null);
              txfLocation.setBounds(new Rectangle(5,95,200,25));
                   panAddItem.add(txfLocation, null);
              btnLocation.setBounds(new Rectangle(210,95,100,25));
                   btnLocation.setActionCommand("Find");          // Button for JFileChooser
                   btnLocation.addActionListener(this);
                   panAddItem.add(btnLocation, null);
              optTimer.setBounds(new Rectangle(5,125,100,25));
                   optTimer.setActionCommand("optTimer");
                   optTimer.addActionListener(this);
                   btgTimer.add(optTimer);
                   panAddItem.add(optTimer, null);
              optTimeDef.setBounds(new Rectangle(105,125,100,25));
                   optTimeDef.setActionCommand("optTimeDef");
                   optTimeDef.addActionListener(this);
                   btgTimer.add(optTimeDef);
                   panAddItem.add(optTimeDef, null);
              optNull.setActionCommand("optNull");
                   optNull.addActionListener(this);
                   btgTimer.add(optNull);
              lblTimer.setBounds(new Rectangle(5,155,100,25));
                   panAddItem.add(lblTimer, null);
              txfTimer.setBounds(new Rectangle(5,185,100,25));
                   panAddItem.add(txfTimer, null);
              lblTimeDef.setBounds(new Rectangle(105,155,100,25));
                   panAddItem.add(lblTimeDef, null);
              btnTimeDef.setBounds(new Rectangle(105,185,100,25));
                   panAddItem.add(btnTimeDef, null);
              btnAdd.setBounds(new Rectangle(210,155,100,25));
                   btnAdd.setActionCommand("Add");
                   btnAdd.addActionListener(this);
                   panAddItem.add(btnAdd, null);
              btnCancel.setBounds(new Rectangle(210,185,100,25));
                   btnCancel.setActionCommand("Cancel Add");
                   btnCancel.addActionListener(this);
                   panAddItem.add(btnAdd, null);
         } // End of addNewInit()
         public void findFile()
              fcLocation.setFileSelectionMode(JFileChooser.FILES_AND_DIRECTORIES);
              int iLocation = fcLocation.showOpenDialog(fraAddItem);
              if(iLocation == JFileChooser.APPROVE_OPTION)
                   txfLocation.setText(fcLocation.getCurrentDirectory() + "\\" + fcLocation.getSelectedFile().getName());
                   System.out.println(fcLocation.getSelectedFile().getName() + " selected");
              else
                   System.out.println("No file selected.");
                   return;
         } // End of findFile()

    The problem is with he registration of actionListener for the find button.
    This is being done in your code each time the AddNewItem is being
    used. because of this each time you click Add New Item. another listener
    is registered for the find button and hence the no. of times it will
    show filechooser will keep on increasing.
    Pravin

  • JFileChooser - FireFox on OS X - showSaveDialog returns immediately or hang

    I have a singed applet that uses the JFileChooser to allow the suer to pick a file location. This works with FF and IE on Windows, works with Safari on OS X and used to work with FF on OS X. However a bug was just discovered where it no longer works with FF on OS X.
    JFileChooser chooser = new JFileChooser();
    // ask the user where we should save the file
    chooser.setCurrentDirectory(new File(System.getProperty("user.home")));
    System.out.println("*************************** "+System.getProperty("user.home"));
    chooser.setSelectedFile(new File(attachmentName));
    chooser.setDialogTitle("Save Attachment - " + attachmentName);
    int returnVal = chooser.showSaveDialog(null);
    System.out.println("*************************** "+returnVal);
    Doing the above I either get a complete hange of the broswer and VM or the showSaveDialog call returns immediately with a value of ERROR_OPTION and then the dialog is displayed.
    It doesn't seems to make a difference where I put the above code.
    We were supposed to do a release of the software today but this is a show stopper. Any help would be great.

    I've now tried the following:
    public void doit() {
    Runnable getTextFieldText = new Runnable() {
    public void run() {
    System.out.println("%%%%%%%%%%%%%%%%%%%%%%%%%% 1 "+ SwingUtilities.isEventDispatchThread() );
    JFileChooser chooser = new JFileChooser();
    System.out.println("%%%%%%%%%%%%%%%%%%%%%%%%%% 2 "+ SwingUtilities.isEventDispatchThread() );
    chooser.setCurrentDirectory(new File(System.getProperty("user.home")+"/Desktop/"));
    System.out.println("%%%%%%%%%%%%%%%%%%%%%%%%%% 3 "+ SwingUtilities.isEventDispatchThread() );
    chooser.setSelectedFile(new File("fred"));
    System.out.println("%%%%%%%%%%%%%%%%%%%%%%%%%% 4 "+ SwingUtilities.isEventDispatchThread() );
    chooser.setDialogTitle("Save Attachment - ");
    System.out.println("%%%%%%%%%%%%%%%%%%%%%%%%%% 5 "+ SwingUtilities.isEventDispatchThread() );
    int returnVal = chooser.showSaveDialog(null);
    System.out.println("@@@@@@@@@@@@@@@@@@@@@@@@@@@@ "+returnVal);
    try{
    SwingUtilities.invokeLater(getTextFieldText);
    }catch(Exception x){
    x.printStackTrace();
    Which works everywhere except FF which hang after the user dismisses the dialog. I'm begging for any insight here.

Maybe you are looking for