JFileChooser.showSaveDialog: All files greyed out - java

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.

Related

java JFileChooser how to temporarily disable file selection window

Is there a way how to temporarily disable file chooser in the JFileChooser window?
I created custom preview JPanel and I need the next file selection to be made only after the file preview is done/created (it created image from Wavefront OBJ files when such obj file is selected in the file chooser window).
Maybe some sort of disabling the whole file selection window part?
EDIT:
I was searching around here a bit more and found post Start a JFileChooser with files ordered by date. Now if I understood it right, then according to it, this piece of code should in fact enabling access to FilePane inside the JFileCHooser (of course, I downloaded the SwingUtils.java class first):
JTable table = SwingUtils.getDescendantsOfType(JTable.class, fileChooser).get(0);
But when I do that, I got error in NetBeansIDE saying: java.lang.IndexOutOfBoundsException: Index: 0, Size: 0
Does anyone know why?
I also found post How to disable file input field in JFileChooser?, according to which this piece of code accessing the JFileChooser's textfield showing the selected file name:
import java.awt.Frame;
import java.lang.reflect.Field;
import javax.swing.JFileChooser;
import javax.swing.JFrame;
import javax.swing.JTextField;
import javax.swing.plaf.metal.MetalFileChooserUI;
public class FileChooser {
public static void main(String[] args) throws Exception{
Frame f = new JFrame();
JFileChooser jFileChooser = new JFileChooser();
MetalFileChooserUI ui = (MetalFileChooserUI)jFileChooser.getUI();
Field field = MetalFileChooserUI.class.getDeclaredField("fileNameTextField");
field.setAccessible(true);
JTextField tf = (JTextField) field.get(ui);
tf.setEditable(false);
tf.setEnabled(false);
jFileChooser.showDialog(f, "Select");
f.dispose();
}
}
So, by inspecting all available fields I found out there is one called "filePane". So I took a risk and try to imitate the above code just with a few changes so that the FilePane would be targeted instead like this:
Field fieldB = MetalFileChooserUI.class.getDeclaredField("filePane");
fieldB.setAccessible(true);
FilePane filePane = (FilePane) fieldB.get(ui);
filePane.setEnabled(false);
I thought the code above would disable the file selection part of the JFileChooser window, but it did absolutely nothing, unfortunately.
So after a while I've solved it myself by playing further with the above code ending up with this functioning piece below:
FilePane filePane = SwingUtils.getDescendantsOfType(FilePane.class, fileChooser).get(0);
filePane.setEnabled(false);//<- this line doesn't work, but I'll leave it here so others know
filePane.setVisible(false);

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.

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.

Malformed Farsi characters on AWT

When I started programming with the JDK6, I had no problem with text components, neither in AWT nor in Swing.
But for labels or titles of AWT components I do have a problem. I can't display Farsi characters on AWTs components (in Swing I type them into the source code).
Here's my sample code:
import javax.swing.*;
import java.awt.*;
import java.io.*;
import java.util.Properties;
public class EmptyFarsiCharsOnAWT extends JFrame{
public EmptyFarsiCharsOnAWT() {
super("مثال");
setDefaultCloseOperation(3);
setVisible(rootPaneCheckingEnabled);
}
public static void main(String[] args) throws AWTException, IOException {
JFrame jFrame = new EmptyFarsiCharsOnAWT();
MenuItem show ;
// approach 1 = HardCoding :
/*
show = new MenuItem("\u0646\u0645\u0627\u06cc\u0634");
*
*/
// approach 2 = using simple utf-8 saved text file :
/*
BufferedReader in = new BufferedReader(new FileReader("farsiLabels.txt"));
String showLabel = in.readLine();
in.close();
show = new MenuItem(showLabel);
*
*/
// approach 3 = using properties file :
FileReader in = new FileReader("farsiLabels.properties");
Properties farsiLabels = new Properties();
farsiLabels.load(in);
show = new MenuItem(farsiLabels.getProperty("tray.show"));
PopupMenu popUp = new PopupMenu();
popUp.add(show);
// creating Tray object
Image iconIamge = Toolkit.getDefaultToolkit().getImage("greenIcon.png");
TrayIcon trayIcon = new TrayIcon(iconIamge, null, popUp);
SystemTray tray = SystemTray.getSystemTray();
tray.add(trayIcon);
jFrame.setIconImage(iconIamge);
}
}
These three approaches all work when run with an IDE, but when I make a JAR containing this class (by means of NetBeans > project > clean & build), I don't see the expected characters (it shows EMPTY/BLANK SQUARES)!
Note:
It seems I can not attach anything, so the contents of the text file would be this: نمایش and the contents of properties file:
#Sun May 02 09:45:10 IRDT 2010
tray.show=نمایش
And I think I have to let you know that I posted this question a while ago on SDN and "the Java Ranch" forums and other native forums and still I'm waiting...
By the way I am using latest version of Netbeans IDE...
I will be grateful if anybody has a solution to these damn AWT components never rendering any Farsi character for me...
I suspect that this is platform related. Your example appears to work on my platform using approach 1 in either Netbeans or the command line; I didn't try the other approaches.
There might be a disparity between the IDE and the command line with regard to the default character encoding. I've noticed that NetBeans, Eclipse and many consoles can be set to something other than the platform default. Here's code to check:
System.out.println(System.getProperty("file.encoding"));
System.out.println(Charset.defaultCharset().name());
You might look at this related question, too.
Addendum: Note show string changed to match the JFrame title for comparison. The title and menu look the same from NetBeans' Run > Run Project as well as via these command lines:
$ java -cp build/classes EmptyFarsiCharsOnAWT
$ java -jar dist/test6.jar
import javax.swing.*;
import java.awt.*;
import java.io.*;
public class EmptyFarsiCharsOnAWT extends JFrame{
public EmptyFarsiCharsOnAWT() {
super("مثال");
setDefaultCloseOperation(3);
setVisible(rootPaneCheckingEnabled);
}
public static void main(String[] args) throws AWTException, IOException {
JFrame jFrame = new EmptyFarsiCharsOnAWT();
MenuItem show ;
// approach 1 = HardCoding :
show = new MenuItem("\u0645\u062b\u0627\u0644");
PopupMenu popUp = new PopupMenu();
popUp.add(show);
// creating Tray object
Image iconIamge = Toolkit.getDefaultToolkit().getImage("image.jpg");
TrayIcon trayIcon = new TrayIcon(iconIamge, null, popUp);
SystemTray tray = SystemTray.getSystemTray();
tray.add(trayIcon);
jFrame.setIconImage(iconIamge);
}
}
The most exciting part of your reply was:
"$ java -jar dist/test6.jar" !
Does it really shows the real characters (just like the frame title)?!
and not boxes or garbage ?
I'm sorry if I believe it hard, because the only problem in my developing work with Java took such long without any answer nor from searching, nor asking in forums is this!
So, what can I do? what font should I use? Unfortunately I'm not so familiar with fonts, until now I've just used global fonts in Java (Serif,SansSerif,etc.) and only modified their size or style, but after you suggest I examined several Persian ttf fonts through these codes:
File fontFile = new File("F_JADID.TTF");
Font font = Font.createFont(Font.TRUETYPE_FONT, fontFile);
show.setFont(font.deriveFont(15f));
but just boxes was the result! (just using HardCoding)
I think i should mention that my envirounment is win xp and i have this problem not only in my machine, but another running xp os too. And I'm using jdk6u17.
I can be agree with you in suspecting the fonts, because encoding problem (in my experience) appears with question mark, but garbage or empty boxes related to rendering characters.
But still i have the problem, just like the first day :(
What font you use and another question i encountered is:
Why swing doesn't have any problem without specifying the font, but AWT.
Addendum: Thanks to Oscar Reyes in this page for giving this link and thanks to StackOverflow :)
They saved me! from this section i should quote:
An application using peered AWT components can only use logical font names.
and from this section should quote:
For applications using AWT peered components, Sun's JREs select fonts for Chinese, Japanese, or Korean only when running on host operating systems localized for these specific languages
Yes, you guess right! by setting the OS locale to Farsi, i got the right result.
but i still should research and see how is it possible to have the right result by not setting the right locale, from that article.
I will explain how, when i got the result, but still will listen to here. wish me luck.

text in textfield

After selecting file using browse button into textfield and selecting checkbox that checkbox radio buttons and run should be enabled.How can i do this in swing using java code?
Lets start with selecting a file in Swing:
JFileChooser chooser = new JFileChooser();
int choice = chooser.showSaveDialog(MainFrame.this);
if (choice != JFileChooser.APPROVE_OPTION)
return;
File selectedFile = chooser.getSelectedFile();
That block of code will open a File dialog and wait for a user to select a file. Then the selected file will be stored into selectedFile.
You need to better clarify what you are asking for if you need more help.
JFileChooser, suggested by Justin Nelson, has an addActionListener() method. By implementing the ActionListener interface, your actionPerformed() method will be called to signal various user actions. You can enable buttons and set fields there. The tutorial How to Use File Choosers shows several examples.

Categories