JFileChooser Save Dialog

When you call the JFileChooser's showSaveDialog method, what is the best way to allow the user to enter a new file name? It seems like that if they enter a new file name into the text box, getSelectedFile () won't work, so how do you create a new file out of what the user has entered in the text box?

This is how it looks
JFileChooser chooser = new JFileChooser();
cfc(chooser);
private void cfc(JFileChooser fc)
     for(int i=0; i < fc.getComponentCount();i++)
          if (fc.getComponent(i) instanceof JPanel) ojp((JPanel)fc.getComponent(i));
private void ojp(JPanel jp)
     for(int j=0; j < jp.getComponentCount();j++)
          Component bo = jp.getComponent(j);
          if (bo instanceof JPanel) ojp((JPanel)bo);
          if (bo instanceof JButton)
               if (((JButton)bo).getText().equals("Open"))
                    bo.setBackground(Color.green);
               if (((JButton)bo).getText().equals("Cancel"))
                    bo.setForeground(Color.red);
Noah

Similar Messages

  • Set default filename in JFileChooser (Save Dialog)

    Hi,
    how can i set a default filename in a JFileChooser-Save-Dialog?
    The file does NOT exist, so setSelectedFile(new File("FileName")); does not work.
    Thanks in advance.
    Filo

    Did you test this? It works fine for me.

  • JFileChooser as save dialog clears text field on change directory

    I am trying to implement a basic save dialog using JFileChooser, which initiates with an initial file name, "untitled.txt". However, as soon as the directory is changed by the user, the text field is cleared. I want to ensure that whatever is in the text field when the user changes directories (i.e., untitled.txt may have been changed to something else by the user) stays visible throughout any kind of user navigation. I've tried all sorts of things, but nothing seems to work.
    Thanks for your help.

    Yes, it very well could be an OS/JDK issue. I'm using jdk 1.5 on Mac OS X (Tiger). Apparently, FileNameExtensionFilter is a jdk 1.6 implementation, because it doesn't work for me.
    Here's my code:
    JFileChooser fc = new JFileChooser();
    String output = outputTextArea.getText();
            String selectedFile = "untitled.txt";
            File file = new File(selectedFile);
            fc.setDialogTitle("Save");
            fc.setMultiSelectionEnabled(false);
            fc.setFileSelectionMode(JFileChooser.DIRECTORIES_ONLY);
            fc.setSelectedFile(file);
            setFileName(file.getName());
            int result = fc.showSaveDialog(this);
            if (result == JFileChooser.CANCEL_OPTION) {
                return;
            } else if (result == JFileChooser.APPROVE_OPTION) {
                file = fc.getSelectedFile();
                if (file.exists()) {
                    int response = JOptionPane.showConfirmDialog(null,
                            "Overwrite existing file?","Confirm Overwrite",
                            JOptionPane.OK_CANCEL_OPTION,
                            JOptionPane.QUESTION_MESSAGE);
                    if (response == JOptionPane.CANCEL_OPTION) return;
                if (!writeFile(file, output)) {
                    setErrorMessage(ERROR5_1); //Just a custom error message and display.
                    showErrorMessage();
                    return;
            }Is there a workaround if this is an OS or JDK issue?
    Thanks again for your help.

  • Need help adding a default file name in a file chooser of save dialog type

    I need to create a file chooser with save dialog type, how can I add a highlighted default file name into the File Name textfield? As in Microsoft Word, when you want to save a document, a default file name Doc1.doc will appear in the File name text field of the file chooser even when you change to other directories.

    For JRE 1.4.0 you can use this fix:
    public class FileChooserFix implements PropertyChangeListener {
      private String fileName;
       * @see PropertyChangeListener
      public void propertyChange(PropertyChangeEvent ev) {
        JFileChooser chooser = (JFileChooser)ev.getSource();
        if (JFileChooser.FILES_ONLY == chooser.getFileSelectionMode()) {
          if (JFileChooser.SELECTED_FILE_CHANGED_PROPERTY.equals(ev.getPropertyName())) {
            File selectedFile = (File)ev.getNewValue();
            if (selectedFile != null) {
              // remember fileName of selected file
              fileName = selectedFile.getName();
          if (fileName != null &&
              JFileChooser.DIRECTORY_CHANGED_PROPERTY.equals(ev.getPropertyName())) {
            // reset selected file
            File directory = (File)ev.getNewValue();
            chooser.setSelectedFile(new File(directory, fileName));
       * Convenience method to create a fixed file chooser.
       * @return      fixed file chooser
      public static JFileChooser create() {
        JFileChooser chooser = new JFileChooser();
        chooser.addPropertyChangeListener(new FileChooserFix());
        return chooser;

  • Default buttons on save dialog

    Hi all,
    I am working with one application and it has a save dialog box which is implemented using JFileChooser. On the Save dialog box, I see four buttons on the right. First of them is to go up a level, second is to go to home, third is for a new folder and the forth is to display file details. The first three are working fine, but the fourth one does not give any results. It I take my cursor on the button, the tool tip says "details", but when I click on that button, nothing happens. Do I need to do something special in my code to activate "details"??
    Any help would be greatly appreaciated.
    Thanks,
    Namrata

    I posted the same question more than one year ago. No answer yet.

  • [Jtable Unicode and Save Dialog]

    Hi all,
    I'm doing a swing application in which I use Jtable.
    In this Jtable, i want that the user can enter unicode character so
    i do this :
    Font font_unicode = new Font("Arial Unicode MS", Font.PLAIN, 13);
    table.setFont(font_unicode);It works fine : the user can enter japanese character.
    My problem is that when i want to save data that are in my jtable. I want to save it in a txt file(I use a txt filter), I loose unicode character.
    I use a save dialog as you can see :
    JFileChooser chooser = new JFileChooser();
              chooser.setFileFilter(info.main.Filter);
              chooser.setCurrentDirectory(new File("."));
              if (chooser.showSaveDialog(chooser) == JFileChooser.APPROVE_OPTION) {
                   try {
                        BufferedWriter bufferedWriter = new BufferedWriter(new FileWriter(chooser
                                  .getSelectedFile(), false));
                        PrintWriter fileWriter = new PrintWriter(bufferedWriter);
    }I saw that in excel(office) there is a possibility to save in "unicode text" and I would like to know if it's also possible in swing. I really need it.
    I'm waiting for your answer..
    THX

    thanks for your answer but i don't find the code for unicode.
    and also i don't know if it's possible to add code for this :
    BufferedWriter bufferedWriter = new BufferedWriter(new FileWriter(chooser
                                  .getSelectedFile(), false));
                        PrintWriter fileWriter = new PrintWriter(bufferedWriter);

  • Open and Save Dialog Boxes Appear Briefly then Close

    Open and save dialogs on my MDD 867 flash briefly and then close themselves in my administrator account. All the other accounts are fine. This makes me suspect something in the Library. I just did a wipe and install plus Migration Assistant to no avail--which furthers my suspicion of Library problems.
    Anyone have any suggestions which file(s) could be the culprits?

    More than likely it's a conflict/corrupted amongst the various preference (plist) files. Log into a good admin account, backup the bad account's folder, delete the bad account, selecting the save data option (which is stored in /Users/Deleted Users/ as a disk image), recreate the bad account using the same username/password combo, log out and back into the recreated original account. If the problem's solved, open the saved data dmg file in /Users/Deleted Users/, open the /Library/Preferences/ folder from the saved data, open the current /Users/restored account/Library/Preferences/ folder, and slowly copy plist files from the saved data folder to the current one that don't exist in it. Log out and back in to ensure there's no conflict and things still work correctly. Resolving conflicts or identifying corrupt plist files is a laborious process. Good luck.
    See http://discussions.apple.com/thread.jspa?messageID=4703015 for more details on this process.

  • Open and Save dialogs are painfully slow. Is there a solution?

    Open and Save dialogs are painfully slow. Is there a solution?

    I pulled this part out of one of the topics Barney-15E linked to. It absolutely works! The glacially slow Finder response has been driving me batty in Mavericks. Each time I restarted, it would take forever to list the startup drive when I opened it. Open and Save dialogues were also painfully slow to respond. Now they all snap open and list instantly. I used TextWrangler to comment out the line in the file auto_master, then ran the automount command in Terminal.
    Working workaround:
    Use the following statements in Terminal.
    sudo vi /etc/auto_master
    In this file comment out /net with #  (#/net .....)
    sudo automount -vc
    Fixed.
    Confirmed here too both for Preview.app Open file sluggishness and Finder window population. Thanks Snaggletooh_DE!
    Couple of notes:
    (1) Some folks may be more comfortable using a GUI editor like TextWrangler instead of vi
         a) in the Finder use the GO menu and select Go to Folder
         b) type  '/etc' ( without single quotes ) in the Go to folder dialog box and press the Go button
         c) Right ( Control  ) click the auto_master file in the resulting Finder window. Select "Open with...." and use TextWrangler ( your choice )
         d) Comment out the line by inserting a '#' ( pound sign ) as noted in Snaggletooth_DE's instructions
         e) Save the file  ( probably need to authenticate with your admin password  )
         f) Do the 'sudo automount -vc' per Snaggletooth_DE's instructions. Will need to authenticate again.
    (2) Notice Snaggletooth_DE described this as a "workaround" because it bypasses an Apple bug. Presumably most people have not changed their auto_master file and it worked fine in Mountain Lion and prior. In other words: If you haven't done so already, please continue to submit feedback and bug reports to Apple for this issue.
    Kudos to Snaggletooth_DE for figuring out code is trying to look at network ( NFS ) volumes that maybe don't exist.

  • Set default filename for file save dialog

    Hi,
    I am using AxAcroPDF control to view pdf files in windows forms.
    Is there any option to set the default filename in the save dialog?
    Thanks for your help.
    Freedon

    Hi,
    I've found a solution.
    public void Open(string filePath)
    axAcroPDF.LoadFile(filePath);
    //this will set the correct name in the save file dialog.
    axAcroPDF.src = filePath;
    Thanks for your help.
    Freedon

  • Set default filename for file save dialog on Save button click

    Hi,
    I am using AxAcroPDF (version 9.0) control to view pdf files in windows forms (C#). The pdf loads into the viewer in the form. Now, when I click on the Save button in the viewer, a Save dialog pops up with a default filename having complete path info.
    If I have loaded the pdf file into AxAcroPDF viewer with filename:
    "C:\Documents and Settings\KB_Kravi\My Documents\CustomerList.pdf"
    then in the save dialog, the default filename will be:
    "C_Documents_and_Settings_KB_Kravi_My Documents_CustomerList.pdf"
    Is there any option to set the default filename in the save dialog to some short name, instead of this lengthy name?
    Thanks,
    Ravi.

    Hi,
    I've found a solution.
    public void Open(string filePath)
    axAcroPDF.LoadFile(filePath);
    //this will set the correct name in the save file dialog.
    axAcroPDF.src = filePath;
    Thanks for your help.
    Freedon

  • Open and Save dialog boxes are sorted reverse alpahbetically by default

    I have a user that experiences the same frustrating experience every time she restarts Apple Mail. All of her open and save dialog boxes in Mail are sorted from Z to A. She can click the name field to change the sort, but it will return to Z-A if she quits and reopens the program. The Finder is set (and stays) at A-Z. Other applications do not exhibit this problem. I am loathe to reset the preferences since that means having to set up accounts again. Restarting the computer and removing user caches made no difference. Any suggestions?  This is an iMac Mid 2008 running Mac OS X 10.6.8.

    I solved my own question through trial and error.
    Just select "None" on the dropdown selector (see screen capture, above) and the Open/Save dialog will revert to the older version.

  • Open/Save Dialog, 9 min. Beachball Freeze

    I am running OS 10.10.2 on a March 2009 iMac with 8GB RAM and 1TB HD.
    PROBLEM: While working in Illustrator 18 (CC 2014), if I choose File > Open, the Open dialog appears but I get the spinning beachball for 9 minutes before file contents appear. I don't have the same problem in Photoshop or any other app.  But after Googling, I see that a number of people have posted similar Console Log messages (see below) when using in a variety of apps in Yosemite, even in Apple's own Mail app.  This tells me the root problem may not be specific to Illustrator, even though it only affects Illustrator in my case currently.
    WHAT I TRIED:
    1) Moved all Adobe Illustrator related PLISTS and preference files and folders to the Desktop and then launched Illustrator.  I saw Illustrator rebuild new prefs files and all settings reverted back to stock.  This proves my moving of the prefs to the Desktop was successful to cause a rebuild of new prefs and PLISTS. Even so, the BeachBall freeze appeared when I did a File > Open.
    2) Rebooted with SHIFT held down (Safe Mode).  But the beachball problem remains.
    3) Disconnected all USB devices except keyboard/mouse, and turned off WiFi and BlueTooth, and even yanked my Ethernet cable.  I also turned off Time Machine and Default Folder.  But the problem remains, even through a reboot.
    4) I removed DropBox and GoogleDrive and I closed all apps other than Illustrator, but to no avail.
    5) Tried a Guest User, but that doesn't work with Adobe Apps.  Ditto for a Standard user.  You get an error dialog when you try to launch Adobe apps with that kind of user.  So I then created an Admin user.  Illustrator's Open dialog box displays files perfectly, as normal!  A NEW ADMIN USER FIXES THE PROBLEM!
    So a new Admin user fixes the beachball problem in the Open dialog, but for my normal Admin user there's the 9 min. beachball problem.  And yet, SAFE MODE doesn't fix the problem while in my normal User.  And neither does deleting Illustrator prefs.  So it's clear there's still something lurking in my primary user account that is absent in the new Admin user account.  But what?  And how can I find it?  (Migrating everything to a new User account is no easy task.)
    Pertinent section of CONSOLE system.log:
    Mar  6 13:27:03 iMac.local WindowServer[151]: disable_update_likely_unbalanced: UI updates still disabled by application "Adobe Illustrator CC 2014" after 15.00 seconds (server forcibly re-enabled them after 1.00 seconds). Likely an unbalanced disableUpdate call.
    Mar  6 13:27:19 iMac.local NetAuthSysAgent[858]: DNSAddressResolver:Resolve CFNetServiceResolveWithTimeout failed
    Mar  6 13:27:19 iMac.local NetAuthSysAgent[858]: ERROR: AFP_GetServerInfo - connect failed 64
    Mar  6 13:27:49 iMac.local NetAuthSysAgent[858]: DNSAddressResolver:Resolve CFNetServiceResolveWithTimeout failed
    Mar  6 13:27:49 iMac.local NetAuthSysAgent[858]: ERROR: AFP_GetServerInfo - connect failed 64
    Mar  6 13:28:19 iMac.local NetAuthSysAgent[858]: DNSAddressResolver:Resolve CFNetServiceResolveWithTimeout failed
    Mar  6 13:28:19 iMac.local NetAuthSysAgent[858]: ERROR: AFP_GetServerInfo - connect failed 64
    Mar  6 13:28:24 iMac.local com.apple.SecurityServer[56]: Session 100025 created
    Mar  6 13:28:49 iMac.local NetAuthSysAgent[858]: DNSAddressResolver:Resolve CFNetServiceResolveWithTimeout failed
    Mar  6 13:28:49 iMac.local NetAuthSysAgent[858]: ERROR: AFP_GetServerInfo - connect failed 64
    Mar  6 13:29:19 iMac.local NetAuthSysAgent[858]: DNSAddressResolver:Resolve CFNetServiceResolveWithTimeout failed
    Mar  6 13:29:19 iMac.local NetAuthSysAgent[858]: ERROR: AFP_GetServerInfo - connect failed 64
    the above repeats while time elapses (I deleted this part for brevity)
    Mar  6 13:35:40 iMac.local mds[33]: (Volume.Normal:2464) volume:0x7f9823863800 ********** Bootstrapped Creating a default store:1 SpotLoc:(null) SpotVerLoc:(null) occlude:0 /Volumes/WORK_SPACE
    Mar  6 13:35:42 iMac com.apple.xpc.launchd[1] (com.apple.TMHelperAgent.SetupOffer): Service only ran for 2 seconds. Pushing respawn out by 8 seconds.
    Mar  6 13:35:42 iMac.local mds[33]: (Volume.Normal:2464) volume:0x7f9824087000 ********** Bootstrapped Creating a default store:1 SpotLoc:(null) SpotVerLoc:(null) occlude:0 /Volumes/GLOBAL_SPACE
    Mar  6 13:35:43 iMac.local WindowServer[151]: common_reenable_update: UI updates were finally reenabled by application "Adobe Illustrator CC 2014" after 534.23 seconds (server forcibly re-enabled them after 1.00 seconds)
    I get the exact same set of messages that you see above every time I try to reproduce the problem, simply by doing a File > Open in Illustrator.
    I assume AFP is Apple File Protocol?  But what "server" is it trying so desperately in vain to "Get"?  And why is a DNS resolver being used?
    Anyway, as you can see from the Console log above, the beachball in the Open/Save dialog in Illustrator goes away after 534 seconds (about 9 min.).  But it reappears each time I try to go to a new folder on my HD within that Open dialog.  Each time takes exactly 534 seconds each time for the stupid beachball to go away when changing folders in the Open dialog. 
    This beachball freeze (for 9 min.) in Illustrator's Open dialog occurred every once and a while over the last several weeks, but now it consistently happens.  And no, I've not installed any new software on my iMac other than Yosemite updates.
    Once again, I would prefer to fix the root problem in my primary user account rather than migrate to a New User even though I now know a new Admin user account resolves the problem.
    Please help.

    With regard to my cry for help...
    Pretty please?
    Here are links to other apps which show the same Console Log messages that I am seeing, proving this is not an issue exclusive to a single app:
    Vmware & OS 10.10.2
    Pertaining to networked HD's
    Shared Mac on a Network
    Prevents Time Capsule access and kills Time Machine too
    OS 10.10 & Time Capsule woes
    OS 10.9.2 & NAS woes
    Yosemite & Time Capsule woes
    iPhoto woes after Migration
    More Time Capsule woes
    Time Machine woes from Germany (translated)
    mDNSResponder stuck in restart loop
    If you read through all the above like I did, you're probably very tired by now.  But if you had the same problem as I do, you would do anything to resolve it, hence my post here.  So again, I plead for your kind help and attention to this problem!
    The above links do tell me one thing, that a "network error" is at the heart of the Console log messages and my problem.  And that remains true even when I've disconnected from the network entirely, leading me to believe that this is some sort of CACHING BUG.  For truly, there is a Time Capsule at my office, and I do use Time Machine (although not saving to the TC but instead to an external FW HD).  So...  It is my guess that Yosemite has cached some network data it doesn't like and tries to access that data from a cache when the Open Dialog appears in Illustrator.  But WHY ILLUSTRATOR in my case?  It makes no sense to me at all.  I would think it should consistently occur in the Open dialogs of all apps, but it's only in Illustrator.
    I did have problems with my Time Machine backups after putting Yosemite on my iMac, but those issues were resolved in the 10.10.2 update.
    In any case, if indeed it is a CACHING BUG, how then would I clear that stupid, evil cache?
    Again, I would appreciate your kind thoughts and advice.
    Thank you!

  • Open and Save Dialogs Slow to Open and Populate

    In all of my apps, the Open and Save dialogs have become very slow to open and populate since installing Snow Leopard, when the machine is connected to a Windows server. Disconnecting from the server solves the problem; reconnecting causes it to reappear.
    This only happens on some of my machines, and not others
    Any thoughts on what this could be. The delay is significant (about 10 seconds in all).

    Roy,
    I've got the same problem. I've been charting the slowness, i.e. the time until the app responds and opens the save dialog box, and most apps hover around 2 minutes of waiting.
    My home network consists of a belkin n+ router (running only with the N radio, and WPA2 security), one ethernet-connected powerbook with a USB-connected hard disk (640GB+), and my MBP connecting by wireless. The USB HD is used as a Time Machine backup disk, and the backups are extremely slow, on the order of 2 GB's per hour at most.
    That said, I called up Apple Tech Support and they had me flash my PRAM, restart the machine, and Reset Safari (since that was the app I called about). These efforts, unfortunately, did not fix the issue.
    I will be passing on the fact that Tech Support's efforts did not solve the problem--maybe they'll get back to me on the issue. If so, I'll post it here.

  • Open/Save Dialog Box SLOW

    My Mac has slowed down to an absolute crawl. I have reinstalled the OS, run Disk Warrior, Disk Utility, removed my preferences folder to see if something in there was actin' up, I've repaired the permissions, etc... Yet in any application (whether it's Photoshop CS 2, Safari, TextEdit, doesn't matter), if I hit "open" from within that application... no exaggeration... it can take anywhere between 45 seconds to a little over a minute for the dialog box to finally appear!
    The last thing I want to do is nuke my machine. I am so tired of that being the solution whenever something can't be fixed.
    Has anyone run into this? Does anyone have any ideas what to do to fix this problem without nuking the machine?
    (this hasn't been a problem at all until, maybe 3 months ago or so... and I've been running Tiger since it was released)

    Holy cow. I am in complete shock.
    ...got up this morning, saw the suggestion 'bout the iDisk, figured I'd give it a try...
    That was it!!! I've had a .mac account for years, have had my iDisk on my desktop for as long as I can remember. I wonder if something from software update somehow made my machine and the iDisk go "screwy" 'cause it started getting excruciatingly bad just a few months ago.
    Thank you, thank you!! My machine has received a gigantic speed boost across the board, and the open/save dialog boxes now appear instantly when I call upon them, all my apps quit instantly now too. This is amazing! [breathes huge sigh of relief]

  • Open/Save Dialog does not show new files?

    Say you are working on a logic file in a folder and you have
    a few audio and movie files in that folder, and you launch
    Logic and via the open/save dialog window you add a few
    files to your song and in that dialog window you can see
    all the files in that folder.
    Then, in the Finder you add a few more files and movies to
    that folder and again use the open/save dialog window to
    add more files BUT the new files you added since launching
    logic are NOT SHOWN in the dialog window ! ?
    What's the deal with that?
    Every other app can show files added since the launch of the
    application, why not Logic?
    PowerBook G4 1GHz   Mac OS X (10.3.9)  

    project manager
    um, yeah.
    Should not need the project manager simply to see new files added to a directory in a Open/Save dialog window since last opening the app.
    I did a scan, a extended scan, opened all the little turn down arrows of the
    full path to the directory I knew there to be the new files and yes, Logic
    shows them there in the "Project manager".
    BUT Logic still does not show the files in the Open/Save dialog windows.
    This is strange because even simple app like TextEdit can show
    new files in it's Open/Save dialog function windows without the need of
    a project manager.
    I have to quit and re-launch each time to see any new files?

Maybe you are looking for

  • Calendar display incorrect

    Hi, I created a crystal report that requests the user to select a date range from a calendar however the calendar  doesn't display properly. it displays the calendar but with code inserted into some of the boxes...and the calendar display looks stran

  • I have downloaded a movie but it will only play for about 5 seconds at a time. It doesn't seem to load in advance. Any suggestions?

    I need help to understand what to do when my movies won't load so that i can watch them without it stopping and starting. Any suggestions?

  • How 'usefull' will TLF be for Flash AS3 projects?

    The size that TLF will add to a flash project is really huge while it's missing some really standard (HTML) features like floating images and tables. So if those feauters will eventually be added (in v2?) the size will even increase more. A simple (n

  • Task Performance Turning

    Hi Gurus, I am running DAC, but my tasks SIL_PurchaseCostFact_full is taking more time to complete. I looked at the throughtput in the session workflow monitor stats its 146(rows/sec) for 200,000 records. The other env the throughput is higher 6699(r

  • Fee for publishing folios/apps as Creative Cloud member?

    I am a Creative Cloud member and want to take 2 or 3 magazines I design online and make them into apps. I know I have to pay Apple a $99 yearly developer fee but is there any fee I need to pay Adobe? It's confusing becuase with my Creative Cluod Memb