JFileChooser causes the application into Busy/Not responding state - java

I am using JFileChooser to browse and load a file.
File chooser is loading properly and /i was able to select the file and load as well.
The issue is soon after opening the JFilechooser, the background window of the application goes in to Busy/Not Responding state. And if I Drag the
file chooser window, the background is not drawing properly. It causes the application into the crash state. Any idea why it happens.
Please find my below code
LoadFileButton.addListener(SWT.Selection, new Listener() {
#Override
public void handleEvent(Event event) {
JFileChooser chooser = new JFileChooser();
chooser.setFileFilter(filterWithoutExtension);
chooser.setAcceptAllFileFilterUsed(false);
chooser.setFileSelectionMode(JFileChooser.FILES_ONLY);
File selectedFile = null;
int returnVal = chooser.showOpenDialog(null);
if (returnVal == JFileChooser.APPROVE_OPTION) {
//Do My Stuff
}
}
});
Please find my FileFilter
FileFilter filterWithoutExtension = new FileFilter() {
#Override
public boolean accept(File f) {
return !f.getName().contains(".");
}
#Override
public String getDescription() {
return "My Description";
}
};

Related

JFileChooser can select any folder apart from the current one?

I am using JFileChooser to allow the user to select a folder. They must be able to view the files in each folder for context. The problem is that I can't select the folder I am when the dialog pops up. (i.e. I click "open" and nothing happens). However, if I switch to another directory and then back to the first one, then I can select it.
public static String selectFolder()
{
final JFileChooser chooser = new JFileChooser() {
public void approveSelection() {
if (getSelectedFile().isFile()) {
return;
} else
super.approveSelection();
}
};
chooser.setCurrentDirectory(new java.io.File("."));
chooser.setDialogTitle("Select Folder");
chooser.setFileSelectionMode( JFileChooser.FILES_AND_DIRECTORIES );
chooser.setAcceptAllFileFilterUsed(false);
chooser.showOpenDialog(null);
File x = chooser.getSelectedFile();
if( x != null )
return x.toString();
return null;
}
public static String selectFolder() {
final JFileChooser chooser = new JFileChooser() {
public void approveSelection() {
if (getSelectedFile().isFile()) {
return;
} else
super.approveSelection();
}
};
chooser.setCurrentDirectory(new java.io.File("."));
chooser.setDialogTitle("Select Folder");
chooser.setFileSelectionMode(JFileChooser.FILES_AND_DIRECTORIES);
chooser.setAcceptAllFileFilterUsed(true);
chooser.setSelectedFile(new java.io.File("."));
chooser.showOpenDialog(null);
File x = chooser.getSelectedFile();
if (x != null)
return x.toString();
return null;
}
you only have to add the line:
chooser.setSelectedFile(new java.io.File("."));
for the sake of being user-friendly, set it to the same as the CurrentDirectory, so that the user sees which directory will be selected when he clicks the button
As per JFileChooser you have to choose a file or folder on the dialog then only it will allow you to click open/save.

JFileChooser click programmatically on open

I have following code to open a JFilechooser
chooser = new JFileChooser();
chooser.setFileSelectionMode(JFileChooser.DIRECTORIES_ONLY);
chooser.setAcceptAllFileFilterUsed(false);
chooser.showOpenDialog(null);
String path = chooser.getSelectedFile().getPath();
What I want to do is programmatically close this dialog. I see the open button, but how can I "press" it programmatically?
This will simulate the user selection and opening of a file:
JFileChooser chooser = new JFileChooser();
chooser.setFileSelectionMode(JFileChooser.DIRECTORIES_ONLY);
chooser.setAcceptAllFileFilterUsed(false);
new Thread(new Runnable() {
#Override
public void run() {
try {
Thread.sleep(100);
} catch (InterruptedException ex) {
Logger.getLogger(YourApplication.class.getName()).log(Level.SEVERE, null, ex);
}
chooser.setSelectedFile(new File("/your/file/path")));
chooser.approveSelection();
}
}).start();
chooser.showOpenDialog(null);
String path = chooser.getSelectedFile().getPath();
The Thread.sleep(100) is ugly, but has to be in there because otherwise, the JFileChooser isn't open yet when approveSelection is called.

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

Java JFileChooser Returns the Selected Directory Instead Of Browsing It

When I double click a directory JFileChooser is not opening that directory i.e. it's not browsing it but it selects the directory and returns.
How can I implement JFileChooser so that it will show the folder's content when I double click?
If setFileSelectionMode(JFileChooser.FILES_ONLY) is set then the behaviour is good as my needs but I have to use FILES_AND_DIRECTORIES.
you can add your own MouseListener
final JFileChooser fileChooser = new JFileChooser();
fileChooser.setFileSelectionMode(JFileChooser.FILES_AND_DIRECTORIES);
fileChooser.addMouseListener(new MouseListener() {
#Override
public void mouseClicked(MouseEvent arg0) {
if(arg0.getClickCount() == 2) {
File file = fileChooser.getSelectedFile();
if(file.isDirectory()) {
fileChooser.setCurrentDirectory(file);
fileChooser.rescanCurrentDirectory();
}
else {
fileChooser.approveSelection();
}
}
}
//Other methods (can be empty)
});
This checks for double clicks and gets the selected file from the JFileChooser checks if that's a directory and if it is follows it, if it's a file it returns the file. Also if you select a directory and hit open it opens the directory.

Handling a JFileChooser window close?

I have a JFileChooser that is created as shown:
JFileChooser chooser = new JFileChooser();
int choosen = chooser.showOpenDialog(fileSelector.this);
if (choosen == JFileChooser.CANCEL_OPTION) {
System.out.println("Closed");
}
If I close the window with out making a selection I get the error:
Exception in thread "main" java.lang.NullPointerException
at fileSelector.fileSelector(fileSelector.java:32)
at createAndControl.main(createAndControl.java:15)
I wanted to know what the proper way to handle this was, what action should I call on window closed to avoid this?
TIA
It's recommended to do it the other way round:
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
#Override
public void run() {
JFileChooser fc = new JFileChooser();
int returnVal = fc.showOpenDialog(null);
if (returnVal == JFileChooser.APPROVE_OPTION) {
File file = fc.getSelectedFile();
//This is where a real application would open the file.
System.out.println("Opening: " + file.getName() + ".\n");
} else {
System.out.println("Open command cancelled by user.\n");
}
}
});
}

Categories