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

Similar Messages

  • How to get latest added file from a folder using apple script

    Hi..
    I am trying to get a latest added file from a folder..and for this i have below script
    tell application "Finder"
        set latestFile to item 1 of (sort (get files of (path to downloads folder)) by creation date) as alias
        set fileName to latestFile's name
    end tell
    By using this i am not able to get latest file because for some files the creation date is some older date so is there any way to get latest file based on "Date Added" column of a folder.

    If you don't mind using GUI Scripting (you must enable access for assistive devices in the Accessibility System Preference pane), the following script should give you a reference to the last item added to any folder. Admittedly not the most elegant solution, but it works, at least under OS X 10.8.2.
    set theFolder to choose folder
    tell application "Finder"
        activate
        set theFolderWindow to container window of theFolder
        set alreadyOpen to exists theFolderWindow
        tell theFolderWindow
            open
            set theInitialView to current view
            set current view to icon view
        end tell
    end tell
    tell application "System Events" to tell process "Finder"
        -- Arrange by None:
        set theInitialArrangement to name of menu item 1 of menu 1 of menu item "Arrange By" of menu 1 of menu bar item "View" of menu bar 1 whose value of attribute "AXMenuItemMarkChar" is "✓"
        keystroke "0" using {control down, command down}
        -- Sort by Date Added:
        set theInitialSortingOrder to name of menu item 1 of menu 1 of menu item "Sort By" of menu 1 of menu bar item "View" of menu bar 1 whose value of attribute "AXMenuItemMarkChar" is "✓"
        keystroke "4" using {control down, option down, command down}
        -- Get the name of the last item:
        set theItemName to name of image 1 of UI element 1 of last scroll area of splitter group 1 of (window 1 whose subrole is "AXStandardWindow")
        -- Restore the initial settings:
        click menu item theInitialSortingOrder of menu 1 of menu item "Sort By" of menu 1 of menu bar item "View" of menu bar 1
        click menu item theInitialArrangement of menu 1 of menu item "Arrange By" of menu 1 of menu bar item "View" of menu bar 1
    end tell
    tell application "Finder"
        set current view of theFolderWindow to theInitialView -- restore the initial view
        if not alreadyOpen then close theFolderWindow
        set theLastItem to item theItemName of theFolder
    end tell
    theLastItem
    Message was edited by: Pierre L.

  • Adding files from another desktop on the same computer

    I am new to this discussion and I did a quick search to see if anything turned up similar to this question. My husband and I have our own desktops on our Mac; he has several songs that I want from his iTunes library and vice versa. We can't figure out how to add files from each other's library to save our lives. When I go to the import section of iTunes, I can get to his desktop, but there is a little stop symbol with a "-" sign next to his music folder. It is probably very simple, but short of burning a disc and doing it that way, I can't figure it out. Any help would be greatly appreciated.
    Jill
    Power PC G5   Mac OS X (10.4.5)  

    The stop/- sign means the folder is read protected. You can only (by default) use his public folder. To transfer items via copying them over the network you would need to log in as an administrator (most likley as his account) remotely. This will give you acccess to all of his folders.
    If you want to copy between folders on the same machine you need to be an administrator. Try logging in with the admin account.
    If you want to just share the music you can do that too. In OS X Preferences -> Sharing -> Firewall -> check the share iTunes Music checkbox.
    In iTunes you would then need to go to iTunes Preferences -> Sharing -> Make sure both the share button and the "Looked for shared music" and "Share my Music are checked" are checked.
    Do this two both machines.
    And you should then see a folder in iTunes with the other music.
    If you are on a network this works out well with out having to duplicate two sets of data/mp3s.
    Hope this helps.
    -J

  • Selecting all files from JFilechooser and renaming them??

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

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

  • Adding files from external HD is really slow (30min for 7,000 songs)

    I have finally mangaged to add files to my laptop from my external HD (which by the way shift+loading itunes never worked for windows) but loading 7,000 songs takes about 30min. Is it because I don't have a high speed USB on my laptop? My USB from my 250gig external has a 2.0 USB. Could that be the reason?

    USB 2.0 is "high speed" USB (480 Mbps). If by chance you are using USB 1.1, then yes, file transfer is going to be dreadfully slow. I couldn't see any information about your PC in your profile but... if you are using USB 1.1 OR if you have an older hard drive (slow RPM and write speeds) you are going to bottleneck. You did mention that you have a laptop; laptops (even newer ones) often use slow drives (4200 RPM drives are common.) A NICE thing to do for read/write speeds is to upgrade your laptop's hard drive to a 7200 RPM drive. You can do that for around $100.00 via newegg.
    ~( ):>
    iMac 233MhZ Biondi blue 96MB of RAM   Mac OS X (10.3.9)  

  • Adding files from another library

    I am trying to add songs to my ipod that I got on my library on my home computer. The songs that I am trying to add are from another computer that has the same version of itunes and is a HP with windows Xp. I know there is a way I can do this because the other computer saw my ipod and put the files on there just fine.
    Thanks

    You'll need to switch to manual update (iPod preferences after the iPod is attached).
    After that, you'll need to drag the songs to the iPod icon in the source panel.
    Good luck!

  • Ok, so I accidently deleted my "recently Added" file!  How do I get it back?

    I accidentally deleted my recently added file from Itunes on my windows vista computer.  How do I get it back?

    It is simply a smart playlist.
    Make another

  • [svn:osmf:] 14905: Adding file missing from previous commit.

    Revision: 14905
    Revision: 14905
    Author:   [email protected]
    Date:     2010-03-22 05:37:59 -0700 (Mon, 22 Mar 2010)
    Log Message:
    Adding file missing from previous commit.
    Added Paths:
        osmf/trunk/apps/samples/framework/OSMFPlayer/src/assets/fonts/
        osmf/trunk/apps/samples/framework/OSMFPlayer/src/assets/fonts/Standard0755.swf
        osmf/trunk/apps/samples/framework/OSMFPlayer/src/assets/fonts/readme.txt

    If you're confident that the DP contains the new file, try deleting the deployment and re-doing it (not the deployment type - just the deployment to your test collection).
    Gerry Hampson | Blog:
    www.gerryhampsoncm.blogspot.ie | LinkedIn:
    Gerry Hampson | Twitter:
    @gerryhampson

  • [svn:osmf:] 14904: Adding file missing from previous commit.

    Revision: 14904
    Revision: 14904
    Author:   [email protected]
    Date:     2010-03-22 05:32:49 -0700 (Mon, 22 Mar 2010)
    Log Message:
    Adding file missing from previous commit.
    Added Paths:
        osmf/trunk/libs/ChromeLibrary/org/osmf/chrome/hint/
        osmf/trunk/libs/ChromeLibrary/org/osmf/chrome/hint/Hint.as

    If you're confident that the DP contains the new file, try deleting the deployment and re-doing it (not the deployment type - just the deployment to your test collection).
    Gerry Hampson | Blog:
    www.gerryhampsoncm.blogspot.ie | LinkedIn:
    Gerry Hampson | Twitter:
    @gerryhampson

  • [svn:osmf:] 10540: Adding file missing from previous commit.

    Revision: 10540
    Author:   [email protected]
    Date:     2009-09-23 11:39:41 -0700 (Wed, 23 Sep 2009)
    Log Message:
    Adding file missing from previous commit.
    Added Paths:
        osmf/trunk/framework/MediaFrameworkFlexTest/org/openvideoplayer/gateways/TestHTMLGateway. as

    If you're confident that the DP contains the new file, try deleting the deployment and re-doing it (not the deployment type - just the deployment to your test collection).
    Gerry Hampson | Blog:
    www.gerryhampsoncm.blogspot.ie | LinkedIn:
    Gerry Hampson | Twitter:
    @gerryhampson

  • How can i add new files to my ipod from a different computer  without losing the added files on my ipod?

    how can i add new files to my ipod touch from a diferent computer without losing the added files already on my ipod?

    Email them? Use DropBox?  What type of files?

  • [svn:osmf:] 10584: Adding a missing file from that last folder structure refactor.

    Revision: 10584
    Author:   [email protected]
    Date:     2009-09-24 17:19:48 -0700 (Thu, 24 Sep 2009)
    Log Message:
    Adding a missing file from that last folder structure refactor.
    Added Paths:
        osmf/trunk/plugins/akamai/AkamaiBasicStreamingPlugin/AkamaiBasicStreamingPlugin.as

    Hello,
    Welcome to MSDN forum.
    I am afraid that the issue is out of support range of VS General Question forum which mainly discusses
    the usage of Visual Studio IDE such as WPF & SL designer, Visual Studio Guidance Automation Toolkit, Developer Documentation and Help System
    and Visual Studio Editor.
    Because your issue is about ASP.NET web application development, I suggest that you can consult your issue on ASP.NET forum:
    http://forums.asp.net/
     for better solution and support.
    Best regards,
    We are trying to better understand customer views on social support experience, so your participation in this interview project would be greatly appreciated if you have time. Thanks for helping make community forums a great place.
    Click
    HERE to participate the survey.

  • [svn:osmf:] 13186: Adding files missing from previous commit.

    Revision: 13186
    Revision: 13186
    Author:   [email protected]
    Date:     2009-12-23 05:26:07 -0800 (Wed, 23 Dec 2009)
    Log Message:
    Adding files missing from previous commit.
    Added Paths:
        osmf/trunk/libs/ChromeLibrary/assets/images/qualityAuto_disabled.png
        osmf/trunk/libs/ChromeLibrary/assets/images/qualityAuto_down.png
        osmf/trunk/libs/ChromeLibrary/assets/images/qualityAuto_up.png
        osmf/trunk/libs/ChromeLibrary/assets/images/qualityManual_disabled.png
        osmf/trunk/libs/ChromeLibrary/assets/images/qualityManual_down.png
        osmf/trunk/libs/ChromeLibrary/assets/images/qualityManual_up.png

    I just checked my original file and it is 30fps...
    Also other clips from the same camera were correctly finalized, just this one clip "disappeared".
    Any ideas anyone?
    Thanks.

  • ITunes freezes when adding music file from smb share

    As title states, if I try to add more than 15/20 files to iTunes, it freezes and there's no turning back.
    All my music is stored on my home-server (running Gentoo/Linux) and I have always used it with success until iTunes 10 came out.
    The only thing I can do is to unmount the remote directory, open iTunes and remove the music.
    I've already tried to upgrade to v10.0.1 but no luck so far.
    Any clue?
    Thank you

    This has gotten to be a real problem for me as well. It freezes for about 40 seconds for each song I add. It even comes up as "not responding" at times in the force quit dialogue box. I rolled back to iTunes 9.2.1 as described here:
    http://discussions.apple.com/thread.jspa?threadID=2603684&tstart=0
    Others have reported this fixing the problem, but it has NOT fixed it for me. I have my media on an SMB share and my library files were on the local hard drive. I tried moving the library files over to the SMB share, but it didn't improve anything.
    I've been using "Activity Monitor" to look at what's going on and there's minimal CPU usage. But I am noticing something odd: the "Reads in" and "Writes out" figures are pretty much the same, which is what I would expect as I'm copying song files from my internal HD to the SMB share. But the "Data read" and "Data written" figures are very different. It's reading over twice as much data as it's writing. Either I'm misunderstanding what I'm looking at or something isn't right here. Anyone with more technical chops care to jump in?
    I'd post a picture, but there doesn't seem to be a way to do this.
    I'm also wondering if there are corrupted plist files or other invisible files that can be deleted and rebuilt? I used "Filebuddy" to unhide the files and found a file in the iTunes folder called "sentinel". Anyone know what that is?

  • Creating text file from SQL with adding counter in Filename.

    Hi,
    I have a requirement for creating the Tesxt files from Oracle DB which i can achieve by ODISQLUNLOAD.
    But tricky part is that i want have a file name+ counter such that Counter should start with 1 for the first file of the day, then 2,... and reset to 1 for every new date.
    e.g. file0001, file0002,file0003,file0004,.... file0100 and so on for one day.
    But when i will create a file on next day it should be created as again file0001, file0002,file0003,file0004,.... file0100 and so on.
    I may be able to achieve this using some variables but unable to think how could i achieve this.
    Any help would be appreciated.
    Thanks and Regards,
    Mahesh

    Hi Mahesh,
    If the files are loaded as one batch process, for instance, by executing a single package, you could perform a looping function and store the counter as a variable. It would be very similar to the blog post here: https://blogs.oracle.com/dataintegration/entry/using_variables_in_odi_creatin - but you would be using the #counter variable in your filename. Each day that the package is run, the counter starts at 1.
    Hope this will fit your needs.
    Enjoy!
    Michael R.

Maybe you are looking for

  • Fed Up with Aperture

    This is my last shot at getting Aperture 3 to work for me. Despite the good efforts and advice of folks here in the Community, and conversations with Apple, I can't get the **** thing to work correctly with Photoshop. Or, I am not using it correctly.

  • Connect using HOSTNAME adapter with DNSalias

    Hi everyone I am trying to test hostname naming method with Instant Client and DNS aliases. According to docs I should be able to: - on database TEST: add 'testdb.domain.com' to SERVICE_NAMES parameter - in DNS: create an Alias named "testdb.domain.c

  • File-xi-rfc scenario

    Hi all, I am working on File-xi-RFC scenario. i have done IR and ID working. Now I have Done test cofiguration there is NO ERROR ......working File is picked .....as mode is delete.......working.. I check in Adapter Monitoring...............there i g

  • Project stock

    Hi guys, We are using MB1B with 415 movement for transfer of stock from U.R. to project stock and then posting goods issue with MIGO.  But with 415 movement also accounting document is getting generated.  What is the siginificance of this document as

  • A workflow (and the limits of the 'module' concept?)

    Often, choices regarding the best shots (when shooting in difficult conditions, e.g. contre-jour) are determined by which picture better supports adjustments. You might want to check if you get better results by lightening the shadows on picture A or