Java: Bug: JFileChooser only showing up sometimes - java

I have a method to open JFileChooser and allow to user to choose a file to later copy the URL of it. However, JFileChooser only shows up sometimes I run the program (?).
I do not understand what is wrong with the code. Thanks in advance.
More clearly: The UI of the JFileChooser does not show up.
String readThisGlos = null;
JFrame parentFrame = new JFrame();
JFileChooser fileChooser = new JFileChooser();
fileChooser.setDialogTitle("Choose");
int userSelection = fileChooser.showOpenDialog(parentFrame);
if (userSelection == JFileChooser.APPROVE_OPTION) {
File fileToSave = fileChooser.getSelectedFile();
readThisGlos = fileToSave.getAbsolutePath();
} else {
// Error
}
System.out.println(readThisGlos);
return readThisGlos;
Edit: I know the method is running, because when I put a System.out.println("//something"); in the beginning of the method, it works.
If I put System.out.println("//something"); between fileChooser and int userSelection, the UI shows up.

I encountered a similar problem once, I cannot even describe my frustration then.
Try this:
Restart computer
In eclipse: File --> Restart
Clean: C:\eclipse\eclipse.exe -vm "C:\Program Files\Java\jdk1.6.0_24\bin" -clean
Change showOpenDialog(parentFrame) to showOpenDialog(null) (as an user suggested, unnecessary things tend to create problems).
Run the program again.

Related

jFileChooser save and cancel buttons are changed (Save will cancel and Cancel will Save) Java

I'm making a simple Download manager in java.
When running the code in mac it works fine, but i went to test it in windows 7, and i got this problem:
If I click in save, it will leave the path to C:\Users\Gui
If I click to cancel, it will change it to C:\Users\Gui\Documents
Code that i'm using:
JFileChooser f = new JFileChooser();
f.setFileSelectionMode(JFileChooser.DIRECTORIES_ONLY);
f.showSaveDialog(null);
tfPath.setText(f.getCurrentDirectory().toString());
Anyone know a solution to this problem?
default directory of JFileChooser is user/documents for example
for me its
C:\Users\Adeel Ahmad\Documents
for you it will be your C:\Users\your_login_account_name\Documents
use setcurrent directory to set the default directory when jfilechooser is opened
f.setCurrentDirectory("C:\somwhere");
Your code calls f.getCurrentDirectory() , which will give you the parent directory of whichever directory you're in when selecting a directory in JFileChooser.DIRECTORIES_ONLY mode.
you might wanna use f.getSelectedFile() this is the reason you are getting C:\Users\Gui\Documents because when you save it,it gets its parent directory
and you can also know user selected save or cancel, JFileChooser.showSaveDialog returns an int which you can compare with constants of JFileChooser
you can take any action on the base of if user selected save or cancel by using
JFileChooser.CANCEL_OPTION or JFileChooser.APPROVE_OPTION(meaning save option)
JFileChooser f = new JFileChooser();
f.setFileSelectionMode(JFileChooser.DIRECTORIES_ONLY);
f.setCurrentDirectory(new File("D:\\"));
int result=f.showSaveDialog(null);
if(result==JFileChooser.APPROVE_OPTION)
tfPath.setText(f.getCurrentDirectory().toString());

Create new folder with user-defined name and location in java

I am using JavaFX to write a script, part of which involves the user selecting an existing project, or creating a new one. In the latter case I have a popup window that prompts the user for a name and a place to save the project. What I hope to do is create a folder in the place that the user specifies with the same name as the project, from here I will save different items to it and load them later. However when I use filechooser to have the user pick the location for the folder it requires them to select an item before the chooser actually picks anything. Then the folder that it makes has the name of this item in the beginning. (For example if I picked the Chrome shortcut on my desktop the folder name would be chrome.exeProject1 or something like that)
I know part of the problem is because I reused part of my filechooser code for a different function where I required the user to have an item selected before they could submit it, anyway...
Is there any way for the user to select a folder, or just submit the filechooser without selecting any items and create the new folder here? (Inside the selected folder or in the current folder in the latter case).
relevant code below, any help is appreciated. Thanks!
#FXML
private void submitName(ActionEvent event) {
name = nameOfProject.getText();
if (name != null && location != null)
{
new File(location + name).mkdir();
}
}
#FXML
private void createProjectDirectory(ActionEvent event) {
FileChooser projectDirectory = new FileChooser();
projectDirectory.setTitle("Create Project Directory:");
File refLocation = projectDirectory.showOpenDialog(null);
if (refLocation != null) {
locationOfProject.clear();
location = refLocation.getPath();
locationOfProject.appendText(location);
}
}
You have to use DirectoryChooser instead of FileChooser to let the user select a directory.
You can read the documentation on how to use these classes here (it's from JavaFX 2, but I guess the interface is mostly the same).

File Load/Save Explorer Java

I was wondering if there is a GUI file explorer package in java to save me some time.
I'm talking about anything like the window you would see when "Browsing" a file in windows for loading into a media player for example.
Something like this:
Please I am asking if a specific package or methods exist to accommodate this. Just saying Jframe and swing is not really what I am looking for.
You are looking for http://docs.oracle.com/javase/tutorial/uiswing/components/filechooser.html
JFileChooser chooser = new JFileChooser();
int option = chooser.showOpenDialog(SimpleFileChooser.this);
if (option == JFileChooser.APPROVE_OPTION) {
statusbar.setText("You opened " + ((chooser.getSelectedFile()!=null) ? chooser.getSelectedFile().getName():"nothing"));
}
else {
statusbar.setText("You canceled.");
}
I searched in Google for something like this however I must not have phrased it correctly.
We have java.awt.FileDialog that uses the native file system explorer(more user friendly) and like fvu said JFileChooser. A tutorial for http://www.tutorialspoint.com/awt/awt_filedialog.htm here.

JFileChooser.showSaveDialog: All files greyed out

I'm trying to use the JFileChooser to get files for loading and saving. The dialog that comes up with openFileDialog() works fine, but when I use the saveFileDialog() method, the dialog window has all the file names greyed out. This happens with or without a FileFilter (my example includes one to better show what I'm seeing).
Here's a minimal program to illustrate:
import javax.swing.JFileChooser;
import javax.swing.JFrame;
import javax.swing.filechooser.FileNameExtensionFilter;
public class Temp extends JFrame {
public static void main(String[] args){
JFrame frame = new JFrame();
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
JFileChooser chooser = new JFileChooser();
FileNameExtensionFilter filter = new FileNameExtensionFilter("Text File", "txt");
chooser.setFileFilter(filter);
frame.setVisible(true);
chooser.showOpenDialog(null);
chooser.showSaveDialog(null);
}
}
Here's what I see in the Open dialog:
Open Dialog
Here's what I see in the Save dialog:
Save Dialog
Despite being greyed out, all the files in the save dialog are selectable.
I'm on Mac/Mountain Lion and Java 7 if it matters.
Is this expected behavior? Is there a way to change this?
(Edit: per comments by MadProgrammer + trashgod below, this appears to be consistent with the look + feel of other (native) Mac apps)
I'm looking for the .txt files to be displayed in the "normal" color while in the save dialog.
That's controlled by the FileChooserUI delegate specific to a particular Look & Feel, e.g. AquaFileChooserUI on Mac OS X. You can use a different L&F, (laboriously) write your own FileChooserUI, or develop a custom File Browser GUI.
What I ended up doing was to use:
JFileChooser chooser = new JFileChooser(...);
chooser.showDialog(myFrame, "Save");
My save dialog looks like a save dialog, and the FileFilter greys out only files that fail its test.
Mmm... I think, that show dialogs the way you do is not the best way
chooser.showOpenDialog(null);
chooser.showSaveDialog(null);
I think that could be generating a conflict. Why don't you try to use a JFrame to help you? Try with this piece of code, just to know if the problem is the saveDialog. Myabe then you can adapt it to your programming requirements.
JFrame parentFrame = new JFrame();
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());
}
As a matter of fact, you could try using the setLookAndFeel, I remember I had this issue working with my Macbook Pro.

JFileChooser: Cannot select Desktop when Selection Mode is File and Directories

I ran into an issue with JFileChooser and wanted to see if there is a workaround.
If the JFileChooser is created and the setFileSelectionMode is FILES_AND_DIRECTORIES, when a user clicks a shortcut button on the left (in XP) such as Desktop or My Documents or drop down to Desktop, the field is not placed in the File Name JTextPane. And when clicking the "Select/Accept" button, nothing happens (because isDirectorySelected() returns false for some reason).
Overriding the approveSeletion does not work because the Event Handler function in BasicFileChooser does not call it.
How would I make it so the Desktop can be selected without having to navigate to it manually, but by clicking the shortcut on the left?
Thanks
In Windows, the desktop is not backed by any file in the file system - it's a shell namespace. So there really isn't anything that JFileChooser could return to you. Yes, I know that there is a folder that contains the desktop for the user - but remember that the desktop actually displays as a composite of the user's desktop and the All Users desktop folder - plus other things that are added by the shell but not part of any folder (like the trash bin). So returning a File object that represents the 'desktop' is pretty much a non-starter.
Long and short: Ask yourself why you need to do this - chances are that you are going to wind up deep into native code territory, dealing with namespace PIDLs and all sorts of nastiness that you may not want to get into (for the life of me, I cannot understand why M$ had to make this stuff so amazingly difficult to use)...
Here's an intro to Windows shell namespaces so you'll have a feel for what's involved:
http://msdn.microsoft.com/en-us/library/cc144090%28v=vs.85%29.aspx
Found the following code in the BasicFileChooserUI:
if (fc.getFileSelectionMode() == JFileChooser.FILES_AND_DIRECTORIES
&& fc.getFileSystemView().isFileSystem(dir)) {
setFileName(dir.getAbsolutePath());
}
So it looks like "special folders" are purposely ignored. The code is in a private method so it would be hard to create you own UI.
As a hack you might be able to add a PropertyChangeListener to the file chooser:
public void propertyChange(final PropertyChangeEvent e)
{
String prop = e.getPropertyName();
if (JFileChooser.DIRECTORY_CHANGED_PROPERTY.equals(prop))
{
JFileChooser fileChooser = (JFileChooser)e.getSource();
File currentDirectory = (File)e.getNewValue();
String directory = currentDirectory.toString();
if (directory.endsWith("Desktop")
|| directory.endsWith("My Documents"))
{
File selectedFile = fileChooser.getSelectedFile();
if (selectedFile == null || ! selectedFile.equals(currentDirectory))
{
fileChooser.removePropertyChangeListener( this );
fileChooser.setSelectedFile( currentDirectory );
fileChooser.addPropertyChangeListener( this );
}
}
}
}

Categories