Is it possible to select multiple directories at once with JFileChooser - java

As the title states, is there a way to select multiple directories at once (all sub-directories immediately within a primary directory) with JFileChooser so I don't have to re-open the file chooser window for each directory?

Once again I've solved my own question after asking it.
The thing that was preventing me from getting it to work previously was I was using the check for multi-select rather than the set for multi-select, and apparently was using that wrong as well as I kept getting an error. Anyway, the working version is below:
class AddDirectory implements ActionListener {
public void actionPerformed(ActionEvent ae) {
File[] theDir = null;
theDir = selectDir();
if(theDir != null) {
for(File z : theDir) {
String[] curRow = { z.toString(), "Waiting"};
dlm.addRow(curRow);
}
}
return;
}
private File[] selectDir() {
JFileChooser fileChooser = new JFileChooser(lastDir);
fileChooser.setMultiSelectionEnabled(true);
fileChooser.setFileSelectionMode(JFileChooser.DIRECTORIES_ONLY);
int showOpenDialog = fileChooser.showOpenDialog(null);
if (showOpenDialog != JFileChooser.APPROVE_OPTION) {
return null;
}
File[] uploadDir = fileChooser.getSelectedFiles();
lastDir = new File(uploadDir[uploadDir.length-1].getParent());
return uploadDir;
}
}
Once I get the directories, they're loaded into a JTable to be modified before running the rest of my code on them.

Related

Java get selected folder path

In application im asking user to choose folder however using code below Im unable to use this input as variable path
public class csvtoxls {
public static void main() throws IOException {
JFileChooser jfc = new JFileChooser(FileSystemView.getFileSystemView().getHomeDirectory());
jfc.setDialogTitle("Wybierz folder do konwersji: ");
jfc.setFileSelectionMode(JFileChooser.DIRECTORIES_ONLY);
jfc.setAcceptAllFileFilterUsed(false);
int returnValue = jfc.showSaveDialog(null);
if (returnValue == JFileChooser.APPROVE_OPTION) {
if (jfc.getSelectedFile().isDirectory()) {
System.out.println("You selected the directory: " + jfc.getSelectedFile());
So in order to achieve this I used function:
public class getpath {
public static String pickPath(JFileChooser fileChooser)
{
String path = null;
/* create a JFrame to be the parent of the file
* chooser open dialog if you don't do this then
* you may not see the dialog.
*/
JFrame frame = new JFrame();
frame.setAlwaysOnTop(true);
// get the return value from choosing a file
int returnVal = fileChooser.showOpenDialog(frame);
// if the return value says the user picked a file
if (returnVal == JFileChooser.APPROVE_OPTION)
path = fileChooser.getSelectedFile().getPath();
return path;
}
}
Variable:
Path workDir = Paths.get(getpath.pickPath(jfc));
The problem with this solution is that user have to choose folder twice wich can easily lead to mistake. Is there way to get this path easier?

Java jfilechooser using FileNameFilter

I cant get jfilechooser to show the files I return from FileNameFilter. It still shows me all the files inside the folder. I believe fileChooser.setSelectedFiles(listOfMatchingFiles); should set what contents are displayed. I've searched the net but have only found examples of how to set what type of file extensions are viewable. Any help is appreciated. Thanks
final String[] currSelection = selecName.split("_");
FilenameFilter fileNames = new FilenameFilter() {
public boolean accept(File dir, String name) {
if (name.startsWith(currSelection[0])) {
return true;
} else {
return false;
}
}
};
JFileChooser fileChooser = new JFileChooser();
File[] listOfMatchingFiles = fileLOcation.listFiles(fileNames);
fileChooser.setCurrentDirectory(fileLOcation);
fileChooser.setSelectedFiles(listOfMatchingFiles);
for (File a : listOfMatchingFiles) {
//displays the set of files according to currSelection[0]
System.out.println(a);
}
fileChooser.setDialogTitle(currSelection[0]);
if (fileChooser.showOpenDialog(null) == JFileChooser.APPROVE_OPTION) {
File fileToVIEW = fileChooser.getSelectedFile();
}

Java FileFilter to select certain directories

I am trying to create a FileFilter that will only allow the user to open a directory that contains a certain file. The use case is that these directories are workspaces that have a file called smart.workspace inside.
Currently my filter is as follows...
class SMARTWorkspaceFilter extends javax.swing.filechooser.FileFilter {
String description = "SMART Workspace";
String fileNameFilter = "smart.workspace";
SMARTWorkspaceFilter() {
}
#Override
public boolean accept(File file) {
log.debug("Testing file: " + file.getName());
if (file.isFile()) {
return false;
}
if (file.isDirectory()) {
File[] files = file.listFiles();
for (File f : files) {
log.debug("Directory: " + f.isDirectory());
log.debug("Name: " + f.getName());
if (f.isDirectory()) {
return true;
}
if (f.getName().equals(fileNameFilter)) {
return true;
}
}
}
return false;
}
#Override
public String getDescription() {
return description;
}
}
Obviously my problem is that to allow the user to navigate to the workspace folder I have to allow for sub directories.
For the file chooser I am using the option DIRECTORIES_ONLY.
Is it possible to only allow the user to select a directory based on the directories contents?
For example the directory 'workspace' exists at C://Folder1/Folder2/wokspace, I would want to allow the FileChooser to 'start' at C:// and allow the user to navigate to the 'workspace' folder and accept it. The FileChooser shouldn't allow the acceptance of Folder1 or Folder2 but still allow the navigation through Folder1 and Folder2.
I dont think you can make the FileFilter differentiate between "files/directories that should be displayed an can be accessed" and "files/directories that can be selected".
A solution for your problem that comes to my mind is: Let the user search/select the smart.workspace file and then navigate from there to the parent folder.
If you need the dialog to do exactly as you described above you will have to get involved in detail with the JFileChooser. Hopefully extending that class gives you enough access to change the behaviour as desired.
Your problem is that your return statements are conflicting. You don't need the first if statement as you're returning false by default (unless it's a directory AND that directory contains the special file).
class SMARTWorkspaceFilter extends javax.swing.filechooser.FileFilter {
String description = "SMART Workspace";
String fileNameFilter = "smart.workspace";
SMARTWorkspaceFilter() {
}
#Override
public boolean accept(File file) {
log.debug("Testing file: " + file.getName());
// have we selected a directory
if(file.isDirectory()) {
File[] files = file.listFiles();
// for all files in the directory
for(File f : files) {
log.debug("Directory: " + f.isDirectory());
log.debug("Name: " + f.getName());
// if the name is the name of the special file, return true
if(f.getName().equals(fileNameFilter)) {
return true;
}
}
}
// else, return false
return false;
}
#Override
public String getDescription() {
return description;
}
}
Ultimately #SebastianH is correct, it doesn't seem possible through the FileFilter. instead I extended the JFileChooser.
javax.swing.JFileChooser fileChooser = new javax.swing.JFileChooser(defaultLocation){
#Override
public boolean isDirectorySelectionEnabled() {
setOpenButtonState(this, false);
File file = getSelectedFile();
if(file == null){
return false;
}
if(file.isDirectory()){
File[] files = file.listFiles();
for(File f : files){
if(f.isFile() && f.getName().equals("smart.workspace")){
setOpenButtonState(this, true);
return true;
}
}
}
return false;
}
private void setOpenButtonState(java.awt.Container c, boolean flag) {
int len = c.getComponentCount();
for (int i = 0; i < len; i++) {
java.awt.Component comp = c.getComponent(i);
if (comp instanceof javax.swing.JButton) {
javax.swing.JButton b = (javax.swing.JButton)comp;
if ( b != null && b.getText() != null && b.getText().equals("Open") ) {
b.setEnabled(flag);
}
} else if (comp instanceof java.awt.Container) {
setOpenButtonState((java.awt.Container) comp, flag);
}
}
}
};
In addition to preventing the selection I added the nicety of disabling the Open button to avoid confusion.
Credit for the disabling open button --> Disable Open button in JFileChooser?

Reload EditorPane

I found here: what I was searching for but still I have some issues.
This is my action code:
private void jMenuItem1ActionPerformed(java.awt.event.ActionEvent evt) throws IOException {
jEditorPane1.setContentType("text/html");
int returnVal = FileChooser1.showOpenDialog(this);
if (returnVal == FileChooser1.APPROVE_OPTION) {
String image = String.format("<img src=\"%s\">", FileChooser1.getSelectedFile());
jEditorPane1.setText(image);
}
}
Here is a screenshot of what happens, as you can see the image is not loaded.
http://postimg.org/image/agc665ih1/
But if I save the file (with save button) and reopen the same file (with open button), the image is there and is perfectly loaded.
I already tried the .repaint() and .revalidate() methods, but is not working..
Any idea?
This may be problem in setting up path in JEditorPane page. use this:
String image = String.format("<img src=\"%s\">", FileChooser1.getSelectedFile().getPath());
I am assuming that you have already selected appropriate editorKit for JEditorPane.
So now I can answer with my code. I am using this class for the file chooser:
import java.io.File;
import javax.swing.filechooser.FileFilter;
class jpgfilter extends FileFilter {
public boolean accept(File file) {
return file.isDirectory() || file.getAbsolutePath().endsWith(".jpg");
}
public String getDescription() {
return "JPG image (*.jpg)";
}
}
And in my main class I have this:
FileChooser1 = new javax.swing.JFileChooser();
FileChooser1.setDialogTitle("Choose your image:");
FileChooser1.setFileFilter(new jpgfilter());
And that's it.
So I actually found some kind of a solution but I think there is really too much code and that I should do it easily..I actually insert the image and simultaneously save and open the content of the EditorPane as .html file.
The code:
jEditorPane1.setContentType("text/html");
int returnVal = FileChooser1.showOpenDialog(this);
if (returnVal == FileChooser1.APPROVE_OPTION) {
String image = String.format("<img src=\"%s\">", FileChooser1
.getSelectedFile().getPath());
jEditorPane1.setText(image);
String type = jEditorPane1.getContentType();
OutputStream os = new BufferedOutputStream(new FileOutputStream(
"/Library/java_test/temp" + ".html"));
Document doc = jEditorPane1.getDocument();
int length = doc.getLength();
if (type.endsWith("/rtf")) {
// Saving RTF - use the OutputStream
try {
jEditorPane1.getEditorKit().write(os, doc, 0, length);
os.close();
} catch (BadLocationException ex) {
}
} else {
// Not RTF - use a Writer.
Writer w = new OutputStreamWriter(os);
jEditorPane1.write(w);
w.close();
}
String url = "file:///" + "/Library/java_test/temp" + ".html";
jEditorPane1.setPage(url);
}

how to open file with specific extension in fileDialogue

I am trying to Open a file with specific extension ( .fcg or .wtg ) using file Dialog
is there a way to do it ??
If you can use JFileChooser you can use JFileChooser.addChoosableFileFilter() to filter files by extension.
JFileChooser fileChooser = new JFileChooser();
fileChooser.addChoosableFileFilter(new FileFilter() {
#Override
public String getDescription() {
return "*.fct, *.wtg";
}
#Override
public boolean accept(File f) {
return f.getName().endsWith(".fcg") ||
f.getName().endsWith(".wtg");
}
});
You can use this this code to choose a file and read
public void openFile() throws Exception {
int rowCount = 0;
int rowNo = 2;
String id = "";
String name = "";
JFileChooser fc = new JFileChooser();
int result = fc.showOpenDialog(new JPanel());
if (result == JFileChooser.APPROVE_OPTION) {
String file = String.valueOf(fc.getSelectedFile());
File fil = new File(file);
System.out.println("File Selected" + file);
FileInputStream fin = new FileInputStream(fil);
int ch;
while ((ch = fin.read()) != -1) {
System.out.print((char)ch);
}
} else {
}
}
As this is google search #1 for me, this is the solution which worked best for me:
How to restrict file choosers in java to specific files
specifics:
JFileChooser open = new JFileChooser(openPath);
FileNameExtensionFilter filter = new FileNameExtensionFilter("PLSQL Files", "sql", "prc", "fnc", "pks"
, "pkb", "trg", "vw", "tps" , "tpb");
open.setFileFilter(filter);

Categories