Modification to JFileChooser to just display folder content - java

i m trying to develop an gui application which display tree of filesystem on left side and on right side it display selected tree nodes (folder)'s content .
can any body tell me to do modification in jfilechooser to just to display folder content
thank you in advance

The JFileChooser#accept allows you to filter which files are displayed. A similar method is the JFileChooser#setFileFilter method

See: example
JFileChooser fileChooser = new JFileChooser();
fileChooser.setFileSelectionMode(JFileChooser.DIRECTORIES_ONLY);

Perhaps this is what you expected:-
JFileChooser chooser = new JFileChooser();
chooser.setFileSelectionMode(JFileChooser.DIRECTORIES_ONLY);
try {
// Create a File object containing the canonical path of the desired directory
File f = new File(new File(".").getCanonicalPath());
// Set the current directory
chooser.setCurrentDirectory(f);
} catch (IOException e1) {
e1.printStackTrace();
}
// Show the dialog; wait until dialog is closed
int returnVal = chooser.showOpenDialog(frame);
if(returnVal == JFileChooser.APPROVE_OPTION)
{
File f = chooser.getSelectedFile();
textField.setText(f.getAbsolutePath());
File[] contents = f.listFiles();
for(int file=0;file<contents.length;file++)
{
System.out.println(contents[file].getName()); //here you get the contents of the selected directory
}
}

Related

Read images from resource folder of eclipse without using Image name

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.

How to Search All the Files in a Folder with JFileChooser

I have a program that (so far) searches through a file for certain keywords and prints all the lines that have that keyword in it. The problem is it can only search one text file at a time. How can I make it so it searches every text file inside of a folder?
This is the code for the Find File Button that opens just a text file
findFileButton.addActionListener(new ActionListener()
{
#Override
public void actionPerformed(ActionEvent e)
{
JFileChooser fileChoice = new JFileChooser();
fileChoice.setFileSelectionMode(JFileChooser.FILES_ONLY);
int returnVal = fileChoice.showOpenDialog(AdminPanel.this);
if (returnVal == JFileChooser.APPROVE_OPTION)
{
File file = fileChoice.getSelectedFile();
wantedFile = file.getAbsolutePath();
}
}
});
I tried switching the fileSelectionMode to FILES_AND_DIRECTORIES but when i clicked on a folder it would trigger my try/catch for a file wasn't found/specified.
Any help?
Thanks,
~Zmyth
To start with, when using FILES_AND_DIRECTORIES, you will either get a file OR directory. You need to check the type using File.isDirectory to determine what you should do. If it's a directory, then you need to list all the files within it and process them as required, if it's a file, you just need to process it as normal.
If you only want the user to be able to select directories, you could use DIRECTORIES_ONLY
To search the directory...
You could...
Use one of the File#listFiles methods to list all the files from within the selected directory.
This will only list the files for the current directory, if you want to do a recursive search, you need to implement this yourself, but's not to hard
You could...
Use Files#walkFileTree which can be used to walk the current directory and sub directories, depending how you code the FileVisitor
See Walking the File Tree for more details
Sorry if I was unclear in my original question, I wasn't sure how to go about searching for the files in a folder instead of just a file. I was able to get it eventually though with the help of the one answer. I would up vote it but I don't have enough reputation yet. This is what I was looking for:
findFileButton.addActionListener(new ActionListener()
{
#Override
public void actionPerformed(ActionEvent e)
{
JFileChooser fileChoice = new JFileChooser();
fileChoice.setFileSelectionMode(JFileChooser.DIRECTORIES_ONLY);
int returnVal = fileChoice.showOpenDialog(Panel.this);
if (returnVal == JFileChooser.APPROVE_OPTION)
{
File folder = fileChoice.getCurrentDirectory();
File[] listOfFiles = folder.listFiles();
for (int i = 0; i < listOfFiles.length; i++)
{
if (listOfFiles[i].isFile())
{
wantedFilesList.add(listOfFiles[i].getAbsolutePath());
currentFilesList.add(listOfFiles[i].getName());
}
else if (listOfFiles[i].isDirectory())
{
// Blerg
}
}
}
}
});

JFileChooser - open in current directory

I have a simple JFileChooser set up in the following manner
JFileChooser chooser = new JFileChooser();
chooser.setCurrentDirectory(new File("."));
chooser.setFileSelectionMode(JFileChooser.FILES_AND_DIRECTORIES);
chooser.setFileFilter(new FileFilter() {
...
});
int v = chooser.showOpenDialog(this);
if (v == JFileChooser.APPROVE_OPTION) {
File file = chooser.getSelectedFile();
System.out.println(file.getAbsolutePath());
}
As you can see, this FileChooser starts out in the current directory, which in my Netbeans project, is the root of the project folder. Here's the problem: When I select a file and it prints out the absolute path, it includes the "." in the path. For instance, the output I get is:
/Users/MyName/Folder1/Folder2/./Temp.xls
Of course, this is weird, especially since I'm displaying this to the user. Now, I could be hacky and do some fun post substring processing stuff to get rid of that "/./" portion. But...is there a non-lazy programmer way to fix this problem? Thanks in advance!
Use the system property "user.dir" as follows:
File workingDirectory = new File(System.getProperty("user.dir"));
chooser.setCurrentDirectory(workingDirectory);

How to make List with all files in folder using swing?

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

JFileChooser select directory but show files

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.

Categories

Resources