File Load/Save Explorer Java - 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.

Related

Java: Bug: JFileChooser only showing up sometimes

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.

PathMustExists and FileMustExists in SWT FileDialog

To date I only used Swing to build graphical user interfaces but now I also want to make myself familiar with the Standard Widget Toolkit.
I already read the documentation and built a simple app.
My problem is now to use the FileDialog component.
I did the following code:
FileDialog openFileDialog = new FileDialog(shell, SWT.OPEN);
openFileDialog.setFilterExtensions(new String[] { "*.txt" });
openFileDialog.setFilterNames(new String[] { "Text files (*.txt)" });
openFileDialog.setText("Open file");
openFileDialog.open();
But I found no methods to set flags like "PathMustExists" or "FileMustExists".
Is this not possible with FileDialog?
Do I have to extend the class to implement that functionality? If so, how I have to proceed?
Or this there a better OpenFileDialog component (maybe in JFace) from which I don't know?
There are no options for this.
Since you are specifying SWT.OPEN you will get a file dialog specialized for opening existing files. Depending on which platform you are running on this dialog may not allow non-existent files to be selected at all (certainly true on Mac OS X). Still you should check the file after the dialog returns.

JFileChooser in LibGDX

I'm trying to use Javas JFileChooser in my LibGDX scene2d project, but as soon as I launch JFileChooser my program freezes.
Here is the code I use to launch file chooser:
private String getPath(){
String path = "";
fc.setFileSelectionMode(JFileChooser.DIRECTORIES_ONLY);
int returnVal = fc.showOpenDialog(null);
if (returnVal == JFileChooser.APPROVE_OPTION) {
file = fc.getSelectedFile();
try {
path = file.getAbsolutePath();
} catch (Exception ex) {
System.out.println("problem accessing file" + file.getAbsolutePath() + "\n" + ex.getMessage());
}
} else {
System.out.println("File access cancelled by user.");
}
return path;
}
is it swing and libgdx compability problem or is there something I am missing? Same code works perfectly with nativa java projects.
Except instead of: fc.showOpenDialog(null);
I use: fc.showOpenDialog(button); // button is the JButton that triggers the event.
any idea what am I doing wrong?
EDIT: I don't really mind if it wont work on other platforms than Windows.
BUT if I choose to go with cross platform solution, and use LibGDX's method, do I have to create file chooser class with UI from scratch all by myself?
Ok based on your comments from the answer above I get a sense that what you are trying to do is invoke a swing window INSIDE your LibGDX game window, which is an open GL rendering scene.
Let me stop you right there. The swing toolkit invokes its own rendering engine, because it's not intended for this purpose at all - it's intended for desktop applications. So when you instantiate the dialogue, all sorts of other oracle java stuff gets instantiated along with it, like the Graphics2D class. You can't just add this class to a scene2D stage and expect that it draws. They don't implement the same interfaces or inherit from the same base classes. The draw(Graphics2D graphics) method that your JFileChooser implements is not the same as whatever draw(SomeClass foo) method that your libGDX classes implement.
So if you want to make a file chooser window, you need to start looking at the libGDX widget libraries. There might be something that someone has put together already, but my approach for my next libGDX project is going to be to extend these classes for my own UI libraries. I don't know what your project is, or what your timeline is like, but it's certainly a better approach then trying to adapt the swing toolkit to render in an OpenGL rendering scene.
edit
After some quick reading, I'm going to go one further and hazard a guess that the way the swing toolkit gets rendered is entirely dependent on the implementation of the JVM for a specific platform. Now this is where my CS knowledge starts to be a little limited, but I would hazard another guess that this is way way different than the LWJGL implementation of OpenGl by way of using Java wrappers for C libraries.
Personally I dislike the existing FileChooser UIs inside LibGDX. So I created a solution which works using the JFileChooser. Here is some quick and dirty code:
new Thread(new Runnable() {
#Override
public void run() {
JFileChooser chooser = new JFileChooser();
JFrame f = new JFrame();
f.setVisible(true);
f.toFront();
f.setVisible(false);
int res = chooser.showSaveDialog(f);
f.dispose();
if (res == JFileChooser.APPROVE_OPTION) {
//Do some stuff
}
}
}).start();
This will open the FileChooser in front of the LibGDX window without blocking the main Thread. Just tested this on Windows 7, 8, 10 and it only works in window mode ofc.
Coming late to the party but if the point of the question is to invoke a "native" ie. non-gdx file chooser from a libgdx project I made a library to do so here: https://github.com/spookygames/gdx-nativefilechooser.
Example from the readme:
// Configure
NativeFileChooserConfiguration conf = new NativeFileChooserConfiguration();
// Starting from user's dir
conf.directory = Gdx.files.absolute(System.getProperty("user.home"));
// Filter out all files which do not have the .ogg extension and are not of an audio MIME type - belt and braces
conf.mimeFilter = "audio/*";
conf.nameFilter = new FilenameFilter() {
#Override
public boolean accept(File dir, String name) {
return name.endsWith("ogg");
}
};
// Add a nice title
conf.title = "Choose audio file";
fileChooser.chooseFile(conf, new NativeFileChooserCallback() {
#Override
public void onFileChosen(FileHandle file) {
// Do stuff with file, yay!
}
#Override
public void onCancellation() {
// Warn user how rude it can be to cancel developer's effort
}
#Override
public void onError(Exception exception) {
// Handle error (hint: use exception type)
}
});
On the desktop, this example will currently launch an AWT FileDialog (not exactly what is asked) yet a Swing version is currently on the master branch and should be incorporated to the next version of the lib.

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