Java how to play an mp3 file selected from file chooser - java

Hi I have created a file chooser and I am wondering if there is any possible way to play an mp3 file that I can select from my file chooser. If so how can that be implemented ? Thanks for the advice in advance.So Apparently when I click to a file nothing happens what I need is to click on an mp3 file and when I hit open then I can listen to it.
Here is my code for my file chooser.
JFileChooser chooser = new JFileChooser();
File F = new File("C:/");
File namedir;
File namepath;
chooser.setCurrentDirectory(F);
chooser.showOpenDialog(null);
chooser.setDialogTitle("Choose file to play");
chooser.setApproveButtonText("Play");
namedir = chooser.getCurrentDirectory();
namepath = chooser.getSelectedFile();
System.out.print("the name of the the directory is "+namedir.getName());
System.out.print("the name of the the path is "+namepath.getAbsolutePath());
String fileName=null;

String fileName=null;
JFileChooser chooser = new JFileChooser();
FileNameExtensionFilter filter = new FileNameExtensionFilter(
"MP3 Files", "mp3");
chooser.setFileFilter(filter);
int returnVal = chooser.showOpenDialog(parent);
if(returnVal == JFileChooser.APPROVE_OPTION) {
fileName= chooser.getSelectedFile().getName();
}
MediaPlayer mediaPlayer = new MediaPlayer(new Media(fileName));
mediaPlayer.play();
Here's the complete working code
import java.net.URL;
import java.util.concurrent.CountDownLatch;
import java.util.logging.Level;
import java.util.logging.Logger;
import javafx.embed.swing.JFXPanel;
import javafx.scene.media.Media;
import javafx.scene.media.MediaPlayer;
import javax.swing.JFileChooser;
import javax.swing.SwingUtilities;
import javax.swing.filechooser.FileNameExtensionFilter;
/**
*
* #author Mayank Aggarwal
*/
public class MyAudio {
public static void main(String[] args) {
new MyAudio().start();
}
public void start() {
String fileName = null;
URL url;
final CountDownLatch latch = new CountDownLatch(1);
SwingUtilities.invokeLater(new Runnable() {
public void run() {
new JFXPanel(); // initializes JavaFX environment
latch.countDown();
}
});
try {
latch.await();
} catch (InterruptedException ex) {
Logger.getLogger(MyAudio.class.getName()).log(Level.SEVERE, null, ex);
}
JFileChooser chooser = new JFileChooser();
FileNameExtensionFilter filter = new FileNameExtensionFilter(
"MP3 Files", "mp3");
chooser.setFileFilter(filter);
int returnVal = chooser.showOpenDialog(null);
if (returnVal == JFileChooser.APPROVE_OPTION) {
fileName = chooser.getSelectedFile().toURI().toString();
}
MediaPlayer mediaPlayer;
mediaPlayer = new MediaPlayer(new Media(fileName));
mediaPlayer.play();
}
}

Related

Full path of saved file in Java

I want to get the full path of the file that the user saved in Java.
Here is the code of the method save and it works okay but actually i need to get the path that the user had save his file in. Could someone help me:
import java.awt.*;
import java.io.*;
import javax.swing.*;
public class FileChooserSave {
private static void createAndShowUI() {
final JFileChooser chooser = new JFileChooser(new File(".")) {
public void approveSelection() {
if (getSelectedFile().exists()) {
int n = JOptionPane.showConfirmDialog(this, "Do You Want to Overwrite File?", "Confirm Overwrite",
JOptionPane.YES_NO_OPTION);
if (n == JOptionPane.YES_OPTION)
super.approveSelection();
} else
super.approveSelection();
}
};
chooser.setSelectedFile(new File(""));
int returnVal = chooser.showSaveDialog(null);
if (returnVal == JFileChooser.APPROVE_OPTION) {
System.out.println(chooser.getSelectedFile());
}
}
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
public void run() {
createAndShowUI();
}
});
}
}
Here is a sample of java code for absolute path from JFileChoose
JFileChooser fileChooser = new JFileChooser();
fileChooser.setDialogTitle("Specify a file to save");   
 
int userSelection = fileChooser.showSaveDialog(parentFrame);
 
if (userSelection == JFileChooser.APPROVE_OPTION) {
    File fileToSave = fileChooser.getSelectedFile();
    System.out.println("Save as file: " + fileToSave.getAbsolutePath());
}
hope it helps...
You can get the Absolute path using this method:
myFileChooser.getSelectedFile().getAbsolutePath()

JFileChooser doesn't stop running

I've been trying to use JFileChooser but I have the problem that the program doesn't stop running, here's my code:
import java.io.File;
import javax.swing.JFileChooser;
import javax.swing.JFrame;
public class copiarArcivos {
public static void main(String[] args) {
JFileChooser();
}
public static void JFileChooser(){
JFileChooser fileChooser = new JFileChooser();
fileChooser.setCurrentDirectory(new File(System.getProperty("user.home")));
int result = fileChooser.showOpenDialog(new JFrame());
if (result == JFileChooser.APPROVE_OPTION) {
File selectedFile = fileChooser.getSelectedFile();
System.out.println("Selected file: " + selectedFile.getAbsolutePath());
}
}
}
Should I simply put a break at the end of the if?
Don't create an empty JFrame. You can just use null:
//int result = fileChooser.showOpenDialog(new JFrame());
int result = fileChooser.showOpenDialog(null);
You have to change the method name of JFileChooser in main method. and also in the declaration of this method. You can use JFileChooser2 instid of JFileChooser on both.

displaying sagittal and coronal views of dicom image using ImageJ

I am using ImageJ to build a java application which would display a dicom Image.
I was able to import the dicom image and display it successfully. But, I want to display the coronal and sagittal views of the image as well.
Is this possible using ImageJ?
The code to display the dicom image using an applet is what I have below:
// SimpleFileChooser.java
// A simple file chooser to see what it takes to make one of these work.
//
import static com.sun.org.apache.xerces.internal.util.PropertyState.is;
import ij.plugin.DICOM;
import java.applet.Applet;
import java.awt.event.*;
import java.io.*;
import javax.swing.*;
public class readDicom extends Applet {
public void init() {
setSize(350, 200);
JButton openButton = new JButton("Open");
final JLabel statusbar
= new JLabel("Output of your selection will go here");
// Create a file chooser that opens up as an Open dialog
openButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent ae) {
try {
JFileChooser chooser = new JFileChooser();
chooser.setMultiSelectionEnabled(true);
int option = chooser.showOpenDialog(readDicom.this);
if (option == JFileChooser.APPROVE_OPTION) {
File[] sf = chooser.getSelectedFiles();
String filelist = " ";
filelist = sf[0].getName();
File file = chooser.getCurrentDirectory();
String fullpath = file.getCanonicalPath();
fullpath = fullpath + "\\" + filelist;
InputStream reader = new FileInputStream(fullpath);
DICOM dcm = new DICOM(reader);
dcm.run("Name");
dcm.show();
for (int i = 1; i < sf.length; i++) {
filelist += ", " + sf[i].getName();
}
statusbar.setText("You chose " + filelist);
} else {
statusbar.setText("You canceled.");
}
} catch (Exception exception) {
exception.printStackTrace();
}
}
});
this.add(openButton);
this.add(statusbar);
}
}
The Image > Stacks > Orthogonal Views command in ImageJ can do what you need. Have a look at the source code or the javadoc if you want to use its API.

How to save a text file without having to enter file name every time?

Hi all I am creating a simple text editor as a project and I have hit a snag when it comes to saving the content typed as a file. I can save the file using the Save As principle with a dialog box prompting the user to enter a filename.
The problem I am having is implementing the Save so that it saves to the file that is opened without having to go to the dialog box each time, like it would if someone did Ctrl+S. Anyone have any ideas how I would implement this feature?
Here's some of my code:
JMenuItem saveFile = new JMenuItem(new AbstractAction("Save") {
#Override
public void actionPerformed(ActionEvent e) {
JFileChooser save = new JFileChooser();
File filename = save.getSelectedFile();
if(opened == false && saved == false) {
save.showSaveDialog(null);
int confirmationResult;
if(filename.exists()) {
confirmationResult = JOptionPane.showConfirmDialog(getParent(), "Replace existing file?");
if(confirmationResult == JOptionPane.YES_OPTION) {
saveFile(filename);
}
} else {
saveFile(filename);
}
} else {
saveFile(filename);
}
}
});
saveFile.setPreferredSize(new Dimension(100, 20));
saveFile.setEnabled(true);
save method:
private void saveFile(File filename) {
try {
BufferedWriter writer = new BufferedWriter(new FileWriter(filename));
writer.write(textArea.getText());
writer.close();
saved = true;
editorWindow.setTitle("JavaText - " + filename.getName());
} catch (IOException err) {
err.printStackTrace();
}
}
If you store the opened File object somewhere in your application you can then just pass that into your saveFile method on a key press using a KeyListener or KeyAdapter. Without seeing more of the application it's hard to tell where would be best to put it, but if you just store it in a variable somewhere you can refer back to it.
Store the file name somewhere
if(nameOfFile != null) then don't show the dialog box and go to save method
else show dialog box and call the save method
That's what I would do
The following program shows the implementation of 'Save' & 'Save as' functionality for text editors. Running it will shows a JFrame with a JTextArea , save JButton & save as JButton.
import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import javax.swing.JButton;
import javax.swing.JFileChooser;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JTextArea;
public class MyFrame extends JFrame {
private boolean alreadySaved = false;
private BufferedWriter bw;
private JFileChooser fileChooser;
private JTextArea jta;
private File file;
private JButton save;
private JPanel mainPanel;
private JButton saveAs;
public MyFrame() {
initComponents();
save.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent arg0) {
if (!alreadySaved) {
int response = fileChooser.showSaveDialog(getParent());
file = fileChooser.getSelectedFile();
if (response == JFileChooser.APPROVE_OPTION) {
writeFile();
alreadySaved = true;
}
} else
writeFile();
}
});
saveAs.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent arg0) {
int response = fileChooser.showSaveDialog(getParent());
file = fileChooser.getSelectedFile();
if (response == JFileChooser.APPROVE_OPTION) {
writeFile();
alreadySaved = true;
}
}
});
} // END of Constructor
public void writeFile() {
try {
bw = new BufferedWriter(new FileWriter(file));
bw.write(jta.getText());
bw.flush();
} catch (IOException e) {
e.printStackTrace();
}
}
private void initComponents() {
fileChooser = new JFileChooser();
saveAs = new JButton("Save as");
jta = new JTextArea(10, 40);
mainPanel = new JPanel();
mainPanel.setBackground(Color.red);
save = new JButton("Save");
mainPanel.add(save);
mainPanel.add(saveAs);
this.setLayout(new BorderLayout());
this.add(jta);
this.add(mainPanel, BorderLayout.SOUTH);
this.pack();
this.setLocationRelativeTo(null);
}
public static void main(String[] args) {
new MyFrame().setVisible(true);
}
}

How to make JFileChooser Default to Computer View instead of My Documents

In the Windows Look and Feel for JFileChooser, the left hand side of the JFileChooser dialog shows five buttons: Recent Items, Desktop, My Documents, Computer, and Network. These each represent Views of the file system as Windows Explorer would show them. It appears that JFileChooser defaults to the My Documents View unless the setSelectedFile() or setCurrentDirectory() methods are called.
I am attempting to make it easy for the user to select one of a number of mapped network drives, which should appear in the "Computer" View. Is there a way to set the JFileChooser to open the "Computer" view by default?
I have tried a couple methods to force it, the most recent being to find the root directory and set it as the currentDirectory, but this shows the contents of that root node. The most recent code is included below.
private File originalServerRoot;
private class SelectOriginalUnitServerDriveListener implements ActionListener
{
#Override
public void actionPerformed(ActionEvent e)
{
JFileChooser origDriveChooser = new JFileChooser();
origDriveChooser.setFileSelectionMode(JFileChooser.DIRECTORIES_ONLY);
File startFile = new File(System.getProperty("user.dir")); //Get the current directory
// Find System Root
while (!FileSystemView.getFileSystemView().isFileSystemRoot(startFile))
{
startFile = startFile.getParentFile();
}
origDriveChooser.setCurrentDirectory(startFile);
origDriveChooser.setDialogTitle("Select the Mapped Network Drive");
int origDriveChooserRetVal = origDriveChooser.showDialog(contentPane,"Open");
if (origDriveChooserRetVal == JFileChooser.APPROVE_OPTION)
{
originalUnitServerRoot = origDriveChooser.getSelectedFile();
}
}
}
Is there a method that allows me to select the "Computer" view by default (or the Network, or any other view), or any way to trick the JFileChooser?
EDIT
Thanks for the quick and thorough answers. I combined Hovercraft Full Of Eels' and Guillaume Polet's answers to try and make the code work on any drive letter. The resulting code is as follows. Once again, thanks.
private File originalServerRoot;
private class SelectOriginalUnitServerDriveListener implements ActionListener
{
#Override
public void actionPerformed(ActionEvent e)
{
JFileChooser origDriveChooser = new JFileChooser();
origDriveChooser.setFileSelectionMode(JFileChooser.DIRECTORIES_ONLY);
File startFile = new File(System.getProperty("user.dir")); //Get the current directory
// Find System Root
while (!FileSystemView.getFileSystemView().isFileSystemRoot(startFile))
{
startFile = startFile.getParentFile();
}
//Changed the next line
origDriveChooser.setCurrentDirectory(origDriveChooser.getFileSystemView().getParentDirectory(rootFile));
origDriveChooser.setDialogTitle("Select the Mapped Network Drive");
int origDriveChooserRetVal = origDriveChooser.showDialog(contentPane,"Open");
if (origDriveChooserRetVal == JFileChooser.APPROVE_OPTION)
{
originalUnitServerRoot = origDriveChooser.getSelectedFile();
}
}
}
Here is a working example. It makes the assumption that C:\ is a valid path. It uses the FileSystemView.getParentDir(File)
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.File;
import javax.swing.JButton;
import javax.swing.JFileChooser;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.SwingUtilities;
public class Test {
/**
* #param args
*/
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
#Override
public void run() {
new Test().initUI();
}
});
}
protected void initUI() {
JFrame frame = new JFrame();
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
JPanel panel = new JPanel();
final JButton button = new JButton("Select files...");
button.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
final JFileChooser chooser = new JFileChooser();
chooser.setCurrentDirectory(
chooser.getFileSystemView().getParentDirectory(
new File("C:\\")));
chooser.setFileSelectionMode(JFileChooser.DIRECTORIES_ONLY);
chooser.showDialog(button, "Select file");
}
});
panel.add(button);
frame.add(panel);
frame.pack();
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
}
A kludge way to do this is to get the default directory's parent until the toString() of the File obtained is "Computer". something like:
FileSystemView fsv = FileSystemView.getFileSystemView();
File defaultFile = fsv.getDefaultDirectory();
while (defaultFile != null) {
defaultFile = defaultFile.getParentFile();
if (defaultFile != null && "Computer".equalsIgnoreCase(defaultFile.toString())) {
JFileChooser fileChooser = new JFileChooser(defaultFile);
fileChooser.setFileSelectionMode(JFileChooser.DIRECTORIES_ONLY);
int result = fileChooser.showOpenDialog(null);
if (result == JFileChooser.APPROVE_OPTION) {
File file = fileChooser.getSelectedFile();
System.out.println(file);
}
}
}
//Specify the absolute path of the Mapped Drive
chooser.setCurrentDirectory(new File("B:\\exampleFolder"));
OR
// set the file opener to look at the desktop
JFileChooser chooser = new JFileChooser();
chooser.setCurrentDirectory(new File(System.getProperty("user.home") + "\\Desktop"));

Categories