JFileChooser doesn't stop running - java

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.

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()

Window showing in last place rather than first place

When I use JFileChooser, it opens the dialog window in the last place, not in the first place.
It is not showing as the first window = it doesn't "pop up" after I run the program.
It works, when I use it in the main, but when I use it in method, it is doing this.
import javax.swing.JDialog;
import javax.swing.JFileChooser;
public class JFrameChooser {
public static void vyberSuboru() {
JFileChooser fileChooser = new JFileChooser();
JDialog dialog = new JDialog();
int result = fileChooser.showOpenDialog(dialog);
if (result == JFileChooser.APPROVE_OPTION) {
System.out.println(fileChooser.getSelectedFile().getAbsolutePath());
}
}
}
You are creating the file chooser with a newly created dialog which is empty and not visible. Instead use your applications's main window as parent.
Something this way:
public class JFrameChooser {
public static void vyberSuboru(JDialog parent) {
JFileChooser fileChooser = new JFileChooser();
int result = fileChooser.showOpenDialog(parent);
if (result == JFileChooser.APPROVE_OPTION) {
System.out.println(fileChooser.getSelectedFile().getAbsolutePath());
}
}
}

Java how to play an mp3 file selected from file chooser

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();
}
}

Filter file types with JFileChooser

I am using JFileChooser to select a file and I am trying to limit the display to show only jpg or jpeg files. I have tried FileFilter and ChoosableFileFilter and it is not limiting the file selection. Here is my code:
JFileChooser chooser = new JFileChooser();
FileFilter filter = new FileNameExtensionFilter("JPEG file", new String[] {"jpg", "jpeg"});
chooser.setFileFilter(filter);
chooser.addChoosableFileFilter(filter);
int returnVal = chooser.showOpenDialog(null);
if(returnVal == JFileChooser.APPROVE_OPTION) {
debug.put("You chose to open this file: " + chooser.getSelectedFile().getAbsolutePath());
File selectedFile = new File(chooser.getSelectedFile().getAbsolutePath());
...
Try this:
import javax.swing.JFileChooser;
JFileChooser fileChooser = new JFileChooser();
fileChooser.setFileFilter(new FileFilter() {
public String getDescription() {
return "JPG Images (*.jpg)";
}
public boolean accept(File f) {
if (f.isDirectory()) {
return true;
} else {
String filename = f.getName().toLowerCase();
return filename.endsWith(".jpg") || filename.endsWith(".jpeg") ;
}
}
});
Do you mean "it's not limiting the selection" as in "it's allowing the option for any file type"? If so, then try JFileChooser.setAcceptAllFileFilterUsed(boolean).
chooser.setAcceptAllFileFilterUsed(false);
According to the JFileChooser documentation, it should tell it not to add the all-file-types file filter to the file filter list.
Try and use fileChooser.setFileFilter(filter) instead of fileChooser.addChoosableFileFilter(filter).
Try to use fileChooser.setFileFilter(filter) after fileChooser.addChoosableFileFilter(filter), because you need to add your filter to fileChooser and then setting it as default value.
Here is the link with good example:
http://www.java2s.com/Code/Java/Swing-JFC/CustomizingaJFileChooser.htm
Here is a sample code!
private void btnChangeFileActionPerformed(java.awt.event.ActionEvent evt) {
final JFileChooser fc = new JFileChooser();
fc.addChoosableFileFilter(new ArffFilter());
int returnVal = fc.showOpenDialog(this);
...
}
Then
class ArffFilter extends FileFilter {
#Override
public boolean accept(File file) {
if (file.isDirectory()) {
return true;
}
String fileName = file.getName();
int i = fileName.lastIndexOf('.');
if (i > 0 && i < fileName.length() - 1) {
if (fileName.substring(i + 1).toLowerCase().equals("arff")) {
return true;
}
}
return false;
}
#Override
public String getDescription() {
return ".arff (Weka format)";
}
}

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