westofsky159 westofsky159 - 5 days ago 5
Java Question

How to make music list in java?

I choose the music file using JFileChoose.
and I want to add what I choose on frame(in JTextarea)
In that case, I want to list name,time of what i choose.
How to list all of them?
and is that right about what i do something(JTextarea,JFileChoose)?

Answer

You can just implement custome file filtering based on extensions to obtain music file names in a specific directory.

class CustomeFilter implements FilenameFilter {

    @Override
    public boolean accept(File directory, String fileName) {
        boolean valid = false;
        //if (fileName.startsWith("j") ) 
        if ( fileName.endsWith(".mp3") || fileName.endsWith(".wav")) {

            valid = true;
        } else {
            valid = false;
        }

        return valid;
    }

}

The implementation

      File file = new File("C:\\My Music");
      File[] contens = file.listFiles(new CustomeFilter());
        for (File contens : conten) {
            System.out.println(conten);
        }

Then just put the list on any swing components you want.


But if you get the file from the JFileChooser instead, then

public File getCurrentFileInformation() {
        // display file dialog
        JFileChooser fileChooser = new JFileChooser();
        fileChooser.setFileSelectionMode(JFileChooser.FILES_AND_DIRECTORIES);

        int result = fileChooser.showOpenDialog(this);

        // if  Cancel button on dialog clicked, return
        if (result == JFileChooser.CANCEL_OPTION)
            System.exit(1);

        File selectedFileName = fileChooser.getSelectedFile(); // get selected file


        if ((selectedFileName == null) || (selectedFileName.getName().equals(""))) {
            JOptionPane.showMessageDialog(this, "Invalid File Name",
                    "Invalid File Name", JOptionPane.ERROR_MESSAGE);
            System.exit(1);
        } // end if

        return selectedFileName;
    } 

So you get the selected file information with :

File fileInfo = getCurrentFileInformation(); like fileInfo.lastModified() or fileInfo.length()

Comments