Combining File Chooser and this MP3 class

Hello all,
I was curious if anyone could help me figure out how to get a file to actually load once it is used with this code.
I'm unfamiliar with how it works and I was hoping for an explanation on it.
I wasn't sure if I had to have the program recgonize that I would like to load a mp3 or if it just would load it automatically...
Essentially, I want to be able to load a mp3 if I use the file chooser.
I can try to clarify my question more if anyone should need it.
Thank you
import java.io.*;
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
public class List extends JPanel
                             implements ActionListener {
    static private final String newline = "\n";
    JButton openButton, saveButton;
    JTextArea log;
    JFileChooser fc;
    public List() {
        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();
        //Uncomment one of the following lines to try a different
        //file selection mode.  The first allows just directories
        //to be selected (and, at least in the Java look and feel,
        //shown).  The second allows both files and directories
        //to be selected.  If you leave these lines commented out,
        //then the default mode (FILES_ONLY) will be used.
        //fc.setFileSelectionMode(JFileChooser.DIRECTORIES_ONLY);
       // fc.setFileSelectionMode(JFileChooser.FILES_AND_DIRECTORIES);
        //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);
    public void actionPerformed(ActionEvent e) {
        //Handle open button action.
        if (e.getSource() == openButton) {
            int returnVal = fc.showOpenDialog(List.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(List.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 = List.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-dispatching thread.
    private static void createAndShowGUI() {
        //Create and set up the window.
        JFrame frame = new JFrame("FileChooserDemo");
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        //Create and set up the content pane.
        JComponent newContentPane = new List();
        newContentPane.setOpaque(true); //content panes must be opaque
        frame.setContentPane(newContentPane);
        //Display the window.
        frame.pack();
        frame.setVisible(true);
    public static void main(String[] args) {
        //Schedule a job for the event-dispatching thread:
        //creating and showing this application's GUI.
        javax.swing.SwingUtilities.invokeLater(new Runnable() {
            public void run() {
                createAndShowGUI();
}The mp3 class that I've been playing around with...
import java.io.BufferedInputStream;
import java.io.FileInputStream;
import javazoom.jl.player.Player;
public class MP3 {
    private String filename;
    private Player player;
    // constructor that takes the name of an MP3 file
    public MP3(String filename) {
        this.filename = filename;
    public void close() { if (player != null) player.close(); }
    // play the MP3 file to the sound card
    public void play() {
        try {
            FileInputStream fis = new FileInputStream(filename);
            BufferedInputStream bis = new BufferedInputStream(fis);
            player = new Player(bis);
        catch (Exception e) {
            System.out.println("Problem playing file " + filename);
            System.out.println(e);
        // run in new thread to play in background
        new Thread() {
            public void run() {
                try { player.play(); }
                catch (Exception e) { System.out.println(e); }
        }.start();
// test client
    public static void main(String[] args) {
        String filename = "C:\\FP\\1.mp3";
        MP3 mp3 = new MP3(filename);
        mp3.play();
}

Thanks for the link
I've been looking over the sections and still confused with the code.
It's obvious that I have to do something with this portion of the code:
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);
}I'm just not sure what.

Similar Messages

  • File Chooser and Scanner/ PrintWriter

    I'm trying to use the file chooser and scanner and printwriter together. How can I go about this?

    import java.io.*;
    import java.util.Scanner;
    import javax.swing.JFileChooser;
    * @author Originative
    public class Test {
        JFileChooser jf=new JFileChooser(".");
        String fileName="";
        public static void main(String [] nix){
            Test t=new Test();
            t.Actor();
        public void Actor(){
            try{
                Scanner c=new Scanner(System.in);
                System.out.print("Enter 1 to Open JFileChooser : ");
                int k=c.nextInt();
                if(k==1){
                    int val=jf.showOpenDialog(jf);
                    if(val==JFileChooser.APPROVE_OPTION){
                        File fi=jf.getSelectedFile();
                        fileName=jf.getSelectedFile().toString();
                        PrintWriter pw = new PrintWriter(System.out, true);
                        pw.println(fileName);
                if(k!=1){
                    System.out.println("Bye Bye  :)");
            catch(Exception d){
                System.out.println(d);
    }A sample you can use in this way and many many many many others :)

  • Combine Files dialog and File Size

    In the Combine Files dialog box, in the lower right corner, the File Size icons are Small, Default, and Large. These settings are very vague. Does anyone know what the actual settings are that these icons use?

    Throw it away. Go to the [http://commons.apache.org/fileupload] and carefully read both 'User Guide' and 'Frequently Asked Questions' sections.
    And please, please also carefully read this article: [http://balusc.blogspot.com/2008/06/what-is-it-with-roseindia.html].

  • Combining files, assets, and snippets tabs

    I took apart the files, assets, and snippets sidebar windows
    from their single tabbed window, but now I want to put them back
    together. How do I put more than one window on the same tabbed
    window set??
    I see something called "group files with", but it doesn't
    work for windows that are already separated from the main grouped
    windows.

    Have you tried saving your preferred way as a custom workspace?
    If not just try following -
    In DW  CS4 open up the panels in the way you want to and then go to Windows > Workspace Layout > New Workspace.
    Once created you can select this as your default workspace so that each time you open up DW you see same setting.
    Even if somehow it does not open in your custom workspace just go and click it once from the Windows > Workspace Layout (or from the workspace selection icon on the application bar - near top right of screeen.
    Regards,
    Vinay

  • Combination file format and filter plug-in?

    I am working with a file format plug-in. After reading in an image, I want to apply a filter to it. Is it possible to apply the filter from within the file format plug-in?
    Alternatively, is there a means by which one plug-in can start another plug-in?

    You will need to control this all via an automation plug-in. You will need three plug-ins.
    1. The automation plug-in (AMP) will be a listener plug-in and 'listen' for eventOpen with your file format as the class. These needs to happen at Photoshop launch. (See Listener example)
    2. User will open your file and your file format plug-in will run.
    3. Your AMP will get called with the 'eventOpen' 'classMyPlugIn' or whatever you set up.
    4. AMP will now call your filter plug-in.

  • File Choose And download

    Hello friends,
    i read answers to my previous questions and i realized that i
    should probably for the coming time will not use them (though i
    thought they were simple...).
    i want to do something very simple and if you could advise
    how it would be helpful.
    how can i have a page with list of few files (not in 1 place,
    but all on HDD), that user could choose with mouse some of them,
    and than to download them to his local hdd (its internal page to
    small group).
    thank you.

    you are't going to get helpful replies if you don't keep one
    subject in one
    thread. Asking the same question but not giving reference to
    previous
    replies means rehashing the same things.
    > the problem is that its many files, that i want them to
    choose from.
    >the files are in different locations and are constantly
    changing (there is no
    >way to track this...)
    three basic ways-
    Manual updating as documents are added.
    Changing the workflow so these documents are put into ONE
    specific folder,
    which has directory browsing enabled (set
    example.local/documents/ so it
    display folder contents)
    Dynamic page involving a script that reads the contents of
    specified folders
    and builds the page using that info. Assuming that it is a
    known list of
    places where these documents will be. What scripting is
    allowed on this
    intranet? asp/php/?? It is running on a webserver, yes?
    If the documents are added to random folders that contain
    similar files that
    they don't want linked, they need to change the workflow.
    Alan
    Adobe Community Expert, dreamweaver
    http://www.adobe.com/communities/experts/

  • HELLO ALL, I HAVE A POP UP ON ILLUSTRATOR SAYING MISSING PLUG IN SAYING MISSING PDF FILE FORMAT AND THIS IS STOPPING ME OPENING ILLUSTRATOR PLEASE HELP

    Hello all
    Trying to work on illustrator but pop up states i have a plug in missing called pdf file format cannot seem to sort problem, please help, working on mac

    Reinstall the program. This is caused by incompatible updates to Acrobat/ Adobe Reader that introduce new versions of the globally shared PDF libraries.
    Mylenium

  • Custom file chooser

    Hello,
    I need to design a custom file chooser. Infact, I cannot call it a file
    chooser, because this is not accessing local system files. I am uploading
    some files into a directory using ASP and I keep that file name in the database.
    I can even upload directores and directores with files too into the database.
    I need to display those files and folders in the "what is called as file chooser".
    The List should work as it works in file chooser. i.e when I click on a folder,
    it should show the files inside it. When I click on the file, the file should
    be selected. Infact there is nothing in the file. Its all virtual only. Its only
    the name that is selected.
    I should be given an option to select "directories only" also.
    The "file chooser" should not have show files of type, just the file name
    text field only. The combobox should display "user added" string message. And
    this is only one item in the combobox. I should be able to create folders, show
    lists,etc... as it appears in the file chooser. (buttons beside the combobox)
    Any ideas would be greatly appreciated.
    Thanks

    ok, this is just an example....you'll probably need a different constructor and additional methods....
    public class VirtualFile{
      private String file ;
      private VirtualFile[] children;
      private VirtualFile parent;
      public VirtualFile(String file,VirtualFile parent,VirtualFiles[]children){
         this.file = file;
         this.parent = parent;
         this.children = children;
      public boolean isRoot(){
        return parent == null;
      public boolean isDirectory(){
        return children = null || children.length==0;
      public VirtualFile[] getChildren){
        return children;
    }

  • File Chooser + Loops

    I've been at this sadly for almost 8 hours now....here is what my program is suppose to accomplish....yet it's not and I cannot for the life of me figure out what to do
    1. Prompt the user to browse to a file.
    If the user browses to a file, selects it and hits open it will open a JTextArea displaying the text within the file. When the JTextArea closes the program should terminate.
    2. When the user is prompted and selects CANCEL a "catch" statement should then throw a pop-up window telling the user they they did not select a file. When they aknowledge the pop-up they should be prompted to browse to a file. If they continue to hit cancel it should continue to run them through the loop. HOWEVER, when they finally browse and select a file it should work just as I stated in #1.
    3. The same explaination as #2 goes for the catch statement when a users file is unable to be found.
    I have exhausted all online resources, my book, my teacher to try and find how to properly formulate my code and loop to work correctly. This is the best I have come up with.
    It does everything except for one major problem. When a user finally does select a file after running through the loop, it will not display anything.
    Someone please...break this down for me or even edit my code so that I can visually see what and where things go.....I know the reason nothing is being displayed is because in the catch statement I am not stating what to do after the user selects a file....but I dont even think i'm doing this right....sigh
    //  DisplayFile.java       Author: Lewis/Loftus
    //  Demonstrates the use of a file chooser and a text area.
    import java.util.Scanner;
    import java.io.*;
    import javax.swing.*;
    public class FileDisplay
       public static void main (String[] args) throws IOException
          JFrame frame = new JFrame ("Display File");
          frame.setDefaultCloseOperation (JFrame.EXIT_ON_CLOSE);
          JTextArea ta = new JTextArea (20, 30);
          JFileChooser chooser = new JFileChooser();
          int status = chooser.showOpenDialog (null);
         do
             try {
                File  file = chooser.getSelectedFile();
                Scanner scan = new Scanner(file);
                String info = "";
                while (scan.hasNext())
                info +=scan.NextLine() + "\n";
                 ta.setText (info);
              catch (FileNotFoundException exception)
                   JOptionPane.showMessageDialog (null, "File could not be found, click ok to try again");
    chooser.showOpenDialog (null);
              catch (NullPointerException exception)
                   JOptionPane.showMessageDialog (null, "You did not choose a file, click ok to try again");
    chooser.showOpenDialog (null);
         } while (status !=JFileChooser.APPROVE_OPTION);
          frame.getContentPane().add (ta);
          frame.pack();
          frame.setVisible(true);
    }

    No. That's not an assignment statement. To change the value of the variable "status", you need an assignment statement. If being told that isn't helpful, then I suggest you go and talk to your teacher. You won't be able to get anywhere here by asking questions like that.

  • File chooser Very basic

    Hey , i have a simple GUI, a button and a text box. When we click the button a file chooser will appear and we are able to select the folder/file we like.
    My question is, when we click on the button and when the File chooser window appears, i wont it to display the file structure in D:/ShanesFolder/admin/ . how do i code this.
    i ftried using
    FileFilter filter = new FileNameExtensionFilter("c files", "c"); but it filters files only.
    So how can i filter folders in the file chooser, and change the folder location to D:/ShanesFolder/admin/ instead of the default location of the file chosser.

    RTFM
    Do you see anything here that you think might be helpful? [http://java.sun.com/javase/6/docs/api/javax/swing/JFileChooser.html]

  • Using Choose and @inlines commands together

    I am looking for help on how to structure Choose using @inlines. I can get @inlines to work with IF statements and I can get CHOOSE / WHEN to work on it own, but I have a couple of places where I need to use the combination of CHOOSE and INLINES together. I have tried several different options but can't seem to find the magic combination.
    Thanks for any help
    Mattern

    Would this example help?
    <?choose@inlines:?>
    <?when@inlines:EMPLOYEE_NUMBER=''?>No Number<?end when?>
    <?otherwise@inlines:?><?EMPLOYEE_NUMBER?><?end otherwise?>
    <?end choose?>
    Thanks!

  • FXML and Controller base classes?

    Hey Guys,
    Another FXML question: does anyone know if it is possible to get FXMLLoader to pick up the FXML annotations on base classes?
    If we have this:
    public class MyBaseController
        @FXML
        protected Label myLabel1;
    } And this:
    public class MyController extends MyBaseController
        @FXML
        protected Label myLabel2;  
    } And then we load some FXML that references MyController as its controller, it seems only the direct properties on the Controller class are mapped (i.e. 'myLabel2') and not the inherited ones (i.e. 'myLabel1').
    I'm guessing it just hasn't been written this way?
    Greg - I don't suppose sharing the source code for FXMLLoader is an option? It would certainly help us early users work out what we're doing in lieu of more complete docco.
    Cheers,
    zonski

    Just in case anyone is interested, the answer to this question is currently 'no'.
    JIRA issue for it here: http://javafx-jira.kenai.com/browse/RT-16722

  • Have Windows XP and Adobe 9 Reader and need to send a series of large documents to clients as a matter of urgency     When I convert 10 pages a MS-Word file to Pdf this results in file of 6.7 MB which can't be emailed.     Do I combine them and then copy

    I have Windows XP and Adobe 9 Reader and need to send a series of large documents to clients as a matter of urgency When I convert 10 pages a MS-Word file to Pdf this results in file of 6.7 MB which can't be emailed.  Do I combine them and then copy to JPEG 2000 or do I have to save each page separately which is very time consuming Please advise me how to reduce the size and send 10 pages plus quickly by Adobe without the huge hassles I am enduring

    What kind of software do you use for the conversion to pdf? Adobe Reader can't create pdf files.

  • I am having issues suddenly exporting files. It reads error exporting 25 files, As I attempt to choose another destination folder the folders show a black square where the folder sign previously was. I am in my busy season and this has created a huge dela

    I am having issues suddenly exporting files. It reads error exporting 25 files, As I attempt to choose another destination folder the folders show a black square where the folder sign previously was. I am in my busy season and this has created a huge delay!!! HELP!!!!

    oh and if you use a creative cloud version of Lightroom it could also be that the logon to the cloud is messed up. Logging out and logging back in from preferences in the creative cloud app will fix that. Due to the release of Lightroom CC it appears that adobe's servers have been overwhelmed a bit And many people have strange problems that are solved by logging out and back in.

  • WHen I choose an album, upload a file(s), just as the file(s) is uploaded the file I have chosen disappears and I am asked to choose album again. If I ignore this and drag a file onto the sceneline, I get the "where is the file " message" and when click o

    WHen I choose an album, upload a file(s), just as the file(s) is uploaded the file I have chosen disappears and I am asked to choose album again. If I ignore this and drag a file onto the sceneline, I get the "where is the file " message" and when click on the file it is looking for I get the message "This type of file is not supported, or the required codec is not installed". I have made many little films before but always have this problem now. Any suggestions?

    Margaret
    Although we are continents apart - Australia (Perth) vs North America (US), we will not let time zones interfere with getting your Premiere Elements 8.0/8.0.1 working.
    1. The usual Premiere Elements 8 drill.
    a. Are the automatic features of Background Rendering and AutoAnalzyer turned Off?
    For Background Rendering, see Premiere Elements workspace Edit Menu/Preferences/General. For AutoAnalzyer, see Elements Organizer workspace Edit Menu/Preferences/AutoAnalyzer Options.
    b. Are you running the program from the 8.0.1 Update? If not, see Help Menu/Update?
    c. Do you have the latest version of QuickTime installed on your computer with Premiere Elements 8.0/8.0.1?
    Apple - QuickTime - Download
    2. The usual computer drill....for your Windows XP 32 bit (SP3, I presume)
    a. Is computer opitimized, defragmented, etc.
    CCleaner - PC Optimization and Cleaning - Free Download
    b. Are you running your computer from a User Account with Administrative Privileges? That is important for Premiere Elements 8 as well as for its
    required QuickTime. In addition, right click the computer desktop icon for Premiere Elements 8 and select and apply Run As Administrator.
    3. Project Specifics
    For now, import your source media into the project from the computer hard drive using the project's Get Media/Files and Folders. Leave the Elements Organizer and Albums out of the equation for now. We will circle back to it soon after we decide everything else is working as it should be.
    a. You need to set a project preset. And, that project preset should match the properties of your source media. So important to know properties of source media.
    b. When you import your source media into a project you will get a red line over its content if the project preset is not a match - either because you set the wrong one or the program does not have a match for your particular video. That red line means that you are not seeing the best possible preview of what is being played back in the Edit area monitor. To get the best possible preview, you hit the Enter key of the computer main keyboard to get a rendered Timeline (red line goes from red to green after this type of rendering). That green line over your rendered Timeline indicates that you are now getting the best possible preview. This is solely a preview thing. Longer story, but I will leave it at that for now.
    c. Check Edit Menu/Preferences/Scratch Disks to assure that those Scratch Disks are being saved to a computer hard drive location with enough free space to accept them. Make sure that you do not have pile ups of previews files, conformed audio files, and conformed video files.
    See Local Disk C\Documents and Settings\Owner\My Documents\Adobe\Premiere Elements\9.0
    Never move, delete, or rename source files after they have been imported into a project which has been saved/closed. Otherwise, nasty media disconnect problems. You have only copies of media in Premiere Elements. The originals are on the hard drive, and the project must trace back to the originals where they were at import.
    Based on the above, try to start a new project. But, let me know ahead of time what you will be importing into the project. I am looking for
    Video
    video compression
    audio compression
    frame size
    frame rate
    interlaced or progressive
    pixel aspect ratio
    If you do not know, we could try to get that type of information from knowing the brand/model/settings for the camera that recorded the video.
    Photos
    Pixel dimensions and how many photos?
    Lots and lots of details, but eventually they all mellow into one workflow that you can customize for your projects.
    Please do not hesitate to ask questions or to ask for clarification. We can go at whatever pace you feel comfortable with.
    ATR

Maybe you are looking for

  • Printing selected data in ALV or Table in Web Dynpro for ABAP

    Hi Experts, I have ALV  / Table report in the Web Dypro for ABAP App.  User wants to select a record in ALV/ table and / or preview it in PDF form and then he/she can print it. What is the technical steps do I need to achieve this result? Thanks! - A

  • Buy Adobe XI Pro versus Subscription for Adobe XI Pro

    I am the owner of a small CPA firm.  We currently use Adobe 9 Pro which is no longer supported.  I have read through the differences between a subscription to XI Pro vs just upgrading and purchasing.  When I look at the comparison chart I do not see

  • Imac suddenly dropping ISP/INTERNET/SERVER all the time

    Since adding a new Macbook Pro to my home setup my iMac continually drops ISP/INTERNET/SERVER once its connected. All other devices are absolutely fine and connected to BT Home Hub with BT Infinity. When I perform Network Diagnostics it tells NETWORK

  • Weblogic 8.1.6 Unable to load native library: libjvm.so

    hi, i have installed weblogic 8.1 SP6 on my box and when im trying to deploy new application i get errors comaplining about some java libraries. when i link them to the /usr/lib directory it's working but it's not a solution couse i need also weblogi

  • Command Option Left/Right Key Doesn't Work

    10.6.8 Snow Leopard, Command+Option+Left/Right Key stop working. I couldn't move tab, or play previous movie file nor next one. http://codereview.chromium.org/273032 I've tested the other keys work, but just CMD+OPT+Left/Right Arrow hadn't. Is there