I am sure these are very nooby questions... But I have never had to deal with FileDialog before and I can't seem to get my coding to work.
This is my listener for my JButton, which I know it enters because a FileDialog pops up:
public static class FileListener implements ActionListener{
public void actionPerformed(ActionEvent e) {
FileDialog fd = new FileDialog(new Frame(), "Pick Folder");
String dir = "C:/";
fd.setDirectory(dir);
fd.setAlwaysOnTop(true);
fd.setMode(FileDialog.LOAD);
fd.setVisible(true);
String pickedFileDir = fd.getFile();
File folder = new File(pickedFileDir);
File[] listOfFiles = folder.listFiles();
numOfFiles = listOfFiles.length;
}
}
The problem is that I want it to be able to load a FOLDER. I need to get a directory out of it. And even when I do click on 1 file and press "Open" the numOfFiles doesn't change. I know this because of this code:
JLabel number = new JLabel("Files found: " + numOfFiles);
The label doesn't change after opening a file. It should go from "0" to "1".
Much appreciated if you can help me figure this out (obviously a "Best Answer" in there for ya :) )
You should use JFileChooser instead. Here is your example:
JFileChooser jfc = new JFileChooser();
jfc.setFileSelectionMode(JFileChooser.DIRECTORIES_ONLY);
jfc.setCurrentDirectory(new File("C:/"));
if (jfc.showOpenDialog(null) == JFileChooser.APPROVE_OPTION) {
File selectedFile = jfc.getSelectedFile();
File[] listOfFiles = selectedFile.listFiles();
}
Related
I'm creating a program which will create files with different extensions. For that, i'm using the JFileChooser. I've set the FileFilter to accept only my desired extensions, but when I select one, I still have to add the extension in the name of the file myself. How can I solve that? Many thanks!
You basically have to add the extension yourself after the user closes the dialog.
This example allows the user to specify a file ending with ".foo" or ".bar" and will add that extension if the user did not do so.
JFileChooser fileChooser = new JFileChooser();
fileChooser.setMultiSelectionEnabled(false);
fileChooser.removeChoosableFileFilter(fileChooser.getAcceptAllFileFilter());
fileChooser.setFileFilter(new FileNameExtensionFilter("Files ending in .foo", "foo"));
fileChooser.setFileFilter(new FileNameExtensionFilter("Files ending in .bar", "bar"));
int option = fileChooser.showSaveDialog(null);
if (option == JFileChooser.APPROVE_OPTION) {
File file = fileChooser.getSelectedFile();
if (file!=null) {
FileFilter fileFilter = fileChooser.getFileFilter();
if (fileFilter instanceof FileNameExtensionFilter && ! fileFilter.accept(file)) {
// if the filter doesn't accept the filename, that must be because it doesn't have the correct extension
// so change the extension to the first extension offered by the filter.
FileNameExtensionFilter fileNameExtensionFilter = (FileNameExtensionFilter) fileFilter;
String extension = fileNameExtensionFilter.getExtensions()[0];
String newName = file.getName() + "." + extension;
file = new File(file.getParent(), newName);
}
System.out.println("The selected file is: " + file.getAbsolutePath());
}
}
For that you have to get the filefilter selected by the user after he presses the validating button of the JFileChooser and compare the filefilter description with the list of your extensions before initializing the file object with the specified extension in your code if there is a match. I don't know if you will understand me.
Modelexcel model = new Modelexcel();
JFileChooser selectFile = new JFileChooser();;
File file;
JButton btnExporterVersExcel = new JButton("Exporter vers Excel");
btnExporterVersExcel.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
if(selectFile.showDialog(null, "Exporter")==JFileChooser.APPROVE_OPTION) {
String extension=selectFile.getFileFilter().getDescription();
if(extension.contains("(*.xlsx)")) {
file= new File(selectFile.getSelectedFile()+".xlsx");
}else if(extension.contains("(*.xls)")){
file= new File(selectFile.getSelectedFile()+".xls");
}
if(file.getName().endsWith("xls") ||
file.getName().endsWith("xlsx")) {
JOptionPane.showMessageDialog(null, model.Export(file, table));
}else {
JOptionPane.showMessageDialog(null, "Format invalid");
}
}
}
});
This is a fragment of my code to save files in ".xls" and ".xlsx" formats. Hope a look through it will help you
I want to read Images from resource folder of eclipse without using image name. As of now I am reading it from current directory and taking Absolute Path (photoPath) so that I can reproduce the Image in other panel of a JFrame. However if I make executable jar its start taking images from current directory, my image folder is not coming. Here is my Image choosing code
imageChooser = new JButton("ImageChooser");
panel1.add(imageChooser);
fc = new JFileChooser();
imageLabel = new JLabel();
imageChooser.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
fc.setFileSelectionMode(JFileChooser.FILES_AND_DIRECTORIES);
fc.setCurrentDirectory(new File("."));
int result = fc.showOpenDialog(imageChooser);
if (result == JFileChooser.APPROVE_OPTION) {
currentFile = fc.getSelectedFile();
imageLabel.setIcon(new ImageIcon(currentFile.toString()));
panel1.add(imageLabel);
panel1.validate();
photoName=fc.getSelectedFile().getName();
photoPath = currentFile.getAbsolutePath();
}
}
});
Here is my structure
use .getResource()
Example:
new ImageIcon(getClass().getResource("/images/button.png"))
This will work for JAR as well.
I am trying to open a javafx FileChooser in the user directory according to an example I found here.
Here is a fragment of the simple code I am using:
FileChooser fc = new FileChooser();
fc.setTitle("Open Dialog");
String currentDir = System.getProperty("user.dir") + File.separator;
file = new File(currentDir);
fc.setInitialDirectory(file);
However, I keep obtaining this warning (complete file paths have been truncated):
Invalid URL passed to an open/save panel: '/Users/my_user'. Using 'file://localhost/Users/my_user/<etc>/' instead.
I verified that the file object is an existing directory adding these lines:
System.out.println(file.exists()); //true
System.out.println(file.isDirectory()); //true
Then I do not have idea why I am obtaining the warning message.
UPDATE:
This seems to be a bug in JavaFX: https://bugs.openjdk.java.net/browse/JDK-8098160
(you need to create a free Jira account to see the bug report).
This problem happens in OSX, no idea about other platforms.
This is what I ended up doing and it worked like a charm.
Also, make sure your folder is accessible when trying to read it (good practice). You could create the file and then check if you can read it. Full code would then look like this, defaulting to c: drive if you can't access user directory.
FileChooser fileChooser = new FileChooser();
//Extention filter
FileChooser.ExtensionFilter extentionFilter = new FileChooser.ExtensionFilter("CSV files (*.csv)", "*.csv");
fileChooser.getExtensionFilters().add(extentionFilter);
//Set to user directory or go to default if cannot access
String userDirectoryString = System.getProperty("user.home");
File userDirectory = new File(userDirectoryString);
if(!userDirectory.canRead()) {
userDirectory = new File("c:/");
}
fileChooser.setInitialDirectory(userDirectory);
//Choose the file
File chosenFile = fileChooser.showOpenDialog(null);
//Make sure a file was selected, if not return default
String path;
if(chosenFile != null) {
path = chosenFile.getPath();
} else {
//default return value
path = null;
}
This works on Windows and Linux, but might be different on other operating systems (not tested)
Try:
String currentDir = System.getProperty("user.home");
file = new File(currentDir);
fc.setInitialDirectory(file);
#FXML private Label label1; //total file path print
#FXML private Label labelFirst; //file dir path print
private String firstPath; //dir path save
public void method() {
FileChooser fileChooser = new FileChooser();
if (firstPath != null) {
File path = new File(firstPath);
fileChooser.initialDirectoryProperty().set(path);
}
fileChooser.getExtensionFilters().addAll(
new ExtensionFilter("Text Files", "*.txt"),
new ExtensionFilter("Image Files", "*.png", "*.jpg", "*.gif"),
new ExtensionFilter("Audio Files", "*.wav", "*.mp3", "*.aac"),
new ExtensionFilter("All Files", "*.*") );
File selectFile = fileChooser.showOpenDialog(OwnStage);
if (selectFile != null){
String path = selectFile.getPath();
int len = path.lastIndexOf("/"); //no detec return -1
if (len == -1) {
len = path.lastIndexOf("\\");
}
firstPath = path.substring(0, len);
labelFirst.setText("file path : " + firstPath);
label1.setText("First File Select: " + path);
}
}
I want to make a list with filename from a folder and show all the files that are present in that folder with a particular extension. I want the list to be selectable so that I can select and delete the file from the list or edit it. I know how to select all files from a folder but don't know how to show it in GUI.
File folder = new File("c:/");
File[] listOfFiles = folder.listFiles();
This example shows how to enumerate the files in a directory and display them in a JToolBar and a JMenu. You can use an Action, such as RecentFile, to encapsulate behavior for use in your ListModel and ListSelectionListener.
You get all the file name from folder with extension and construct a string
array out of that.Then use a JList to populate in swing.For example something
like below
String options = { "apple.exe", "ball.exe" "cat.exe"};
JList optionList = new JList(options);
Hope this will help you.
See JFileChooser (shameless copy of the JFileChooser help page):
JFileChooser chooser = new JFileChooser();
FileNameExtensionFilter filter = new FileNameExtensionFilter(
"JPG & GIF Images", "jpg", "gif");
chooser.setFileFilter(filter);
int returnVal = chooser.showOpenDialog(parent);
if(returnVal == JFileChooser.APPROVE_OPTION) {
System.out.println("You chose to open this file: " +
chooser.getSelectedFile().getName());
}
See the FilenameFilter?
setMultiSelectionEnabled (true); is another hint.
Location: java/docs/api/javax/swing/JFileChooser.html
I feel like there should be a simple way to do this but I can't figure it out. I have a JFileChooser that allows the user to select directories. I want to show all the files in the directories to give the user some context, but only directories should be accepted as selections (maybe the Open button would be disabled when a file is selected). Is there an easy way of doing this?
My solution is a merge between the answers of camickr and trashgod:
final JFileChooser chooser = new JFileChooser() {
public void approveSelection() {
if (getSelectedFile().isFile()) {
return;
} else
super.approveSelection();
}
};
chooser.setFileSelectionMode( JFileChooser.FILES_AND_DIRECTORIES );
See setFileSelectionMode() in How to Use File Choosers:
setFileSelectionMode(JFileChooser.DIRECTORIES_ONLY)
Addendum: The effect can be see by uncommenting line 73 of this FileChooserDemo, but it appears to be platform-dependent.
Addendum: If using FILES_AND_DIRECTORIES, consider changing the button text accordingly:
chooser.setApproveButtonText("Choose directory");
As the effect is L&F dependent, consider using DIRECTORIES_ONLY on platforms that already meet your UI requirements:
if (System.getProperty("os.name").startsWith("Mac OS X")) {
chooser.setFileSelectionMode(JFileChooser.DIRECTORIES_ONLY);
} else {
chooser.setFileSelectionMode(JFileChooser.FILES_AND_DIRECTORIES);
}
Override the approveSelection() method. Something like:
JFileChooser chooser = new JFileChooser( new File(".") )
{
public void approveSelection()
{
if (getSelectedFile().isFile())
{
// beep
return;
}
else
super.approveSelection();
}
};
The solution of overriding approveSelection can be annoying for certain users.
Sometimes, a user would just click on a file in a directory for no reason (even though she wants to select the directory and not the file). If that happens, the user would be (kind-a) stuck in the JFileChooser as the approveSelection will fail, even if she deselects the file. To avoid this annoyance, this is what I do:
JFileChooser fileChooser = new JFileChooser();
fileChooser.setFileSelectionMode(
JFileChooser.FILES_AND_DIRECTORIES);
int option = fileChooser.showDialog(null,
"Select Directory");
if (option == JFileChooser.APPROVE_OPTION) {
File f = fileChooser.getSelectedFile();
// if the user accidently click a file, then select the parent directory.
if (!f.isDirectory()) {
f = f.getParentFile();
}
System.out.println("Selected directory for import " + f);
}
Selecting the directory, even when the user selected a file results in a better usability in my opinion.
AFAIK JFileChooser separates file filtering (what can be viewed, very configurable) from selection filtering (what can be chosen).
The configuration of selection filtering is much more limited, but AFAIK you can choose to allow only dirs or only files to be selected with setFileSelectionMode()
Keep the fileChooser.setFileSelectionMode(JFileChooser.DIRECTORIES_ONLY) and use:
File[] selectedFiles = fileChooser.getSelectedFile().listFiles();
The JFileChooser supports three selection modes: files only, directories only, and files and directories. In your case what you need is :
JFileChooser fileChooser = new JFileChooser();
fileChooser.setFileSelectionMode(JFileChooser.FILES_AND_DIRECTORIES);
source : http://www.java2s.com/Tutorial/Java/0240__Swing/TheJFileChoosersupportsthreeselectionmodesfilesonlydirectoriesonlyandfilesanddirectories.htm
Select Multiple Folders But Show All Included files
import javax.swing.*;
import java.io.File;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Iterator;
public class MultipleFilesAndDirectoryChooserButDisplayFiles {
public static void main(String[] args) {
ArrayList<File> tempFiles = new ArrayList<>();
ArrayList<File> finalFiles = new ArrayList<>();
ArrayList<String> relativeFiles = new ArrayList<>();
JFileChooser fileChooser = new JFileChooser();
fileChooser.setDialogTitle("Choose File To Transfer");
fileChooser.setFileSelectionMode(JFileChooser.FILES_AND_DIRECTORIES);
fileChooser.setMultiSelectionEnabled(true);
int returnVal = fileChooser.showOpenDialog(null);
fileChooser.approveSelection();
if (returnVal == JFileChooser.APPROVE_OPTION) {
fileChooser.approveSelection();
var fileAddress = fileChooser.getSelectedFiles();
for (var arrElement : fileAddress) {
tempFiles.add(arrElement);
File baseFile;
baseFile = arrElement.getParentFile();
Iterator<File> iterator = tempFiles.iterator();
while (iterator.hasNext()) {
File file = iterator.next();
if (file.isDirectory()) {
var enclosedFiles = file.listFiles();
if (enclosedFiles != null) {
if (enclosedFiles.length != 0) {
var index = tempFiles.indexOf(file);
tempFiles.remove(file);
tempFiles.addAll(index, Arrays.asList(enclosedFiles));
iterator = tempFiles.iterator();
} else {
tempFiles.remove(file);
finalFiles.add(file);
relativeFiles.add(baseFile.toURI().relativize(file.toURI()).getPath());
iterator = tempFiles.iterator();
}
}
} else if (file.isFile()) {
tempFiles.remove(file);
finalFiles.add(file);
relativeFiles.add(baseFile.toURI().relativize(file.toURI()).getPath());
iterator = tempFiles.iterator();
}
}
}
for (var relativeFile : relativeFiles) {
System.out.println(relativeFile);
}
for (var file : finalFiles) {
System.out.println(file);
}
}
}
}
Output:
Folder1/EmptyFolder/
Folder1/SubFolder1/1.1.txt
Folder1/SubFolder1/1.2.txt
Folder1/SubFolder1/1.3.txt
Folder1/SubFolder1/SubFolder 1.1/1.1.1.txt
Folder1/SubFolder1/SubFolder 1.1/1.2.1.txt
Folder1/SubFolder1/SubFolder 1.1/1.3.1.txt
Folder1/SubFolder2/2.1/2.1.1.txt
Folder1/SubFolder2/2.1/2.1.2.txt
Folder1/SubFolder2/2.1/2.1.3.txt
Folder1/SubFolder3/3.1.txt
Folder1/SubFolder3/3.2.txt
Folder1/SubFolder3/3.3.txt
Folder2/Sub Folder/2.1.txt
Folder2/Sub Folder/EmptyFolder/
file1.txt
file2.txt
E:\Folder1\EmptyFolder
E:\Folder1\SubFolder1\1.1.txt
E:\Folder1\SubFolder1\1.2.txt
E:\Folder1\SubFolder1\1.3.txt
E:\Folder1\SubFolder1\SubFolder 1.1\1.1.1.txt
E:\Folder1\SubFolder1\SubFolder 1.1\1.2.1.txt
E:\Folder1\SubFolder1\SubFolder 1.1\1.3.1.txt
E:\Folder1\SubFolder2\2.1\2.1.1.txt
E:\Folder1\SubFolder2\2.1\2.1.2.txt
E:\Folder1\SubFolder2\2.1\2.1.3.txt
E:\Folder1\SubFolder3\3.1.txt
E:\Folder1\SubFolder3\3.2.txt
E:\Folder1\SubFolder3\3.3.txt
E:\Folder2\Sub Folder\2.1.txt
E:\Folder2\Sub Folder\EmptyFolder
E:\file1.txt
E:\file2.txt
I think the best solution is just to allow the user to select either a file or a directory. And if the user select a file just use the directory where that file is located.