JFileChooser - save as

I have a question about jfilechoosers.
I want to save an image, and therefore I use jFileChooser.
my code:
JFileChooser fc = new JFileChooser();
fc.setCurrentDirectory(null);
fc.showSaveDialog(jFrame);
final String selFile = fc.getSelectedFile().toString();here I just keep in a String the path. the saving happens somewhere else, but that not a problem.
my question:
- is it possible to put a name in the textbox? so that the user won't have to type it himself? (just like every normal save as-box, i hope you know what i mean)
thanks!

- is it possible to put a name in the textbox? so that the user won't have to type it himself? (just like every normal save as-box, i hope you know what i mean)There is but I'm forgetting how to do it. It might be with setSelectedFile() or something like that
The main point I wanted to make was that rather than converting your File to a String and then back to a File for saving, just keep it as a File.
>
thanks!

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 Save as Dialog

    I use a JFileChooser to have the user determine where to save a file. My problem is that the "File Name:" text field gets filled with the file path.
    I would much rather this box be left blank, so the user doesn't have to delete the file path in order to type a name.
    Thanks

    here's what it looks like
    http://www.freewebs.com/randopics/Capture.JPG
    I'm trying to make it so that the C:/Users/..... string doesn't show up

  • JFileChooser : save as default file

    I have a JFileChooser which the user uses to pick an excel file that will be imported and displayed in a JTable. I'm looking for a way for the program to save the user's choice as the default, so that every time the application closes and is reopened, he won't have to re-pick the file (unless he is changing it). i'm already using the java.util.prefs class to save other preferences but it seems it only works for primitive data types and so i can't save a "file" to one of the nodes... is there some other way? or am i missing something in the java.util.prefs class?

    pabs123 wrote:
    Though I had found that in the API, i didn't think it was what i was looking for because the problem still remains, how will this file be saved upon closing of the application? I don't know if this has gone off track and maybe the goal which i'm trying to achieve has become lost to you guys but just in case here it is again:
    i have a JTable which must display file "x". I also have a JFilechooser. I want the user to pick a file through the JFileChooser ONE TIME and have that file become the default "x" file. This way when the app is closed, the computer will remember this file and upon startup will import file "x" every time. if the user decides he no longer wants this file but another instead, he can use the JFileChooser to change file "x". what i'm trying to do is save the user the hassle of opening the exact same file every morning (it's a class list).
    maybe i wasn't too clear before but i really appreciate all the help i'm getting, i realize it's a sort of peculiar problem and that's why i came to seek help here where the best reside... hopefully this clears up any misconceptions and helps me find a solution.You aren't too clear now. You said "How will this file be saved upon closing of the application?" but your subsequent verbiage seemed to be talking rather about how to save the name of the file. We've already been through that. You save the name of the file using the java.util.prefs classes. Not the file itself, just the name of the file.
    Or were you really asking about saving the file? You'd use the ordinary Java I/O classes for that. FileWriter and so on.
    Or was your question about how to do something when the application ends?

  • JFileChooser: save file?

    I'm trying to use a JFileChooser to save a file. But in the JFileChooser I see "Open" and "Cancel". How can I change this to eg. "Save as" and "Cancel"?

    Still not reading the API then?
         setApproveButtonText(String approveButtonText)

  • 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

  • Newbie Question: Getting the file name from a JFileChooser

    Hi,
    I have a simple problem.
    I'd like to get the filename that a user types into a JFileChooser Save dialog before they save a file.
    How do I retrieve this name?
    Cheers,
    Chris Share

    Hey it's ok, you're new. But one thing you've got to learn is to RTFM (Read the .... Manual). You'll answer own your questions much faster that way.
    Take a look at the example at the top of:
    http://java.sun.com/j2se/1.5.0/docs/api/javax/swing/JFileChooser.html

  • Strange (Nullpointer) Excep. during Eventdispatching (JFileChooser).

    Hi, sometimes I receive this (complete) stack trace (see below).
    It seems do appear at random, even if no JFilechooser is opened. During initialization of my program there are created some instances of JFilechooser, but I can't figure out what the problem is.
    Cause I taught the setFileSelected action would only take place if you open a Filechooser. But it has been raised, even if there had never been any Filechooser open.
    The first time I received this I thought, it would be an error of the jvm, but then the same error reappeared more than once.
    I'm using the 1.4.1_01 jre.
    It seems to be a problem with the event queue, but what is going wrong.
    Has anyone has ever faced such a problem and can give any clue or idea, how to fix it?
    Any help appreciated.
    Thanks a lot in advance.
    Greetings Michael
    java.lang.NullPointerException
         at javax.swing.plaf.metal.MetalFileChooserUI.setFileSelected(Unknown Source)
         at javax.swing.plaf.metal.MetalFileChooserUI$DelayedSelectionUpdater.run(Unknown Source)
         at java.awt.event.InvocationEvent.dispatch(Unknown Source)
         at java.awt.EventQueue.dispatchEvent(Unknown Source)
         at java.awt.EventDispatchThread.pumpOneEventForHierarchy(Unknown Source)
         at java.awt.EventDispatchThread.pumpEventsForHierarchy(Unknown Source)
         at java.awt.EventDispatchThread.pumpEvents(Unknown Source)
         at java.awt.EventDispatchThread.pumpEvents(Unknown Source)
         at java.awt.EventDispatchThread.run(Unknown Source)

    Hi Leif,
    Hi Michael,
    It could be one of these bugs that are still open:
    http://developer.java.sun.com/developer/bugParade/bugs/4822786.html (no tripple-clicking)
    http://developer.java.sun.com/developer/bugParade/bugs/4759922.html (no file deletion)
    I've read them, but none of them matches my problem exactly.
    If neither of these matches your problem, could you post >a stack trace?The number is changing randomly.
    java.lang.ArrayIndexOutOfBoundsException: Array index out of range: 9
        at java.util.Vector.get(Unknown Source)
        at javax.swing.plaf.basic.BasicDirectoryModel.getElementAt(Unknown Source)
        at javax.swing.plaf.basic.BasicListUI.updateLayoutState(Unknown Source)
        at javax.swing.plaf.basic.BasicListUI.maybeUpdateLayoutState(Unknown Source)
        at javax.swing.plaf.basic.BasicListUI.getCellBounds(Unknown Source)
        at javax.swing.JList.getCellBounds(Unknown Source)
        at javax.swing.JList.ensureIndexIsVisible(Unknown Source)
        at javax.swing.plaf.metal.MetalFileChooserUI.ensureIndexIsVisible(Unknown Source)
        at javax.swing.plaf.metal.MetalFileChooserUI.doDirectoryChanged(Unknown Source)
        at javax.swing.plaf.metal.MetalFileChooserUI.access$2600(Unknown Source)
        at javax.swing.plaf.metal.MetalFileChooserUI$12.propertyChange(Unknown Source)
        at javax.swing.event.SwingPropertyChangeSupport.firePropertyChange(Unknown Source)
        at javax.swing.event.SwingPropertyChangeSupport.firePropertyChange(Unknown Source)
        at javax.swing.JComponent.firePropertyChange(Unknown Source)
        at javax.swing.JFileChooser.setCurrentDirectory(Unknown Source)
        at de.gruenewald.michael.PartyJukebox.PlayList.initFileChoosers(PlayList.java:192)
        at de.gruenewald.michael.PartyJukebox.PlayList.<init>(PlayList.java:96)
        at de.gruenewald.michael.PartyJukebox.PlayList.getReference(PlayList.java:148)
        at de.gruenewald.michael.PartyJukebox.GUI.<init>(GUI.java:91)
        at de.gruenewald.michael.PartyJukebox.GUI.main(GUI.java:217)The Filechooser isn't visible and this exception is risen
    during the startup of the Gui (No clicking!). It occurs very seldom at the start of my app.
    Perhaps this may be caused, by the fileFilters. There may be less files visible than stored in the dir.
    So perhaps some additional code for checking this out could fix this problem.
    Do you mean that you are getting the exception even when >using
    invokeLater()?No, invokeLater uses a Thread and Exception raised their aren't displayed or logged normally, So I can't tell you , if this really solves the problem or if it is just hidden.
    By the way I'm catching the Event-Dispatching-thread, with:
    System.setProperty("sun.awt.exception.handler",HandleAllExceptionOfEventDispatching.class.getName());    I try to use a ThreadLoggingGrooup for the scheduled Thread and will tell you about the results here later (cause of the Exception is really seldom raised.)
    I will also use try to use it for the first problem (NullPointerExcep.).
    SwingUtilities.invokeLater(new Thread(RuntimeObjects.getReference().getLoggingThreadGroup() ,new Runnable(){
                ConfigData config = ConfigData.getReference();
                public void run(){
                    if ( config.getDefaultDirForPlayLists() != null){
                        File file = new File(config.getDefaultDirForPlayLists());
                        if( file.exists() && file.canRead() && file.isDirectory() ){
                            PlayList.this.load.setCurrentDirectory(file);
                            PlayList.this.save.setCurrentDirectory(file);
    public ThreadGroup getLoggingThreadGroup(){
            loggingThreadGroup = new ThreadGroup("LoggingForThreads"){
                PrintStream errLog = RuntimeObjects.getReference().getErrorLog();
                public void uncaughtException(Thread t, Throwable e){
                    if (!(e instanceof ThreadDeath) ){
                        if ( errLog == null){ 
                            errLog.println(e.getMessage());
                            e.printStackTrace(errLog);
                        e.printStackTrace();
            return loggingThreadGroup;
        } Cheers,
    /LeifI also post my initFileChoosers:
    private void initFileChoosers(){
            load = new JFileChooser();
            save = new JFileChooser();
            AllPlaylistsFilter all = new AllPlaylistsFilter();
            PlayListFilter playFilter = new PlayListFilter();
            PlsFilter plsFilter = new PlsFilter();
            M3uFilter m3u = new M3uFilter();
            //save.removeChoosableFileFilter(save.getFileFilter());
            //load.removeChoosableFileFilter(load.getFileFilter());
            save.setAcceptAllFileFilterUsed(false);
            load.setAcceptAllFileFilterUsed(false);
            load.addChoosableFileFilter(all);
            load.addChoosableFileFilter(playFilter);
            load.addChoosableFileFilter(plsFilter);
            load.addChoosableFileFilter(m3u);
            save.addChoosableFileFilter(all);
            save.addChoosableFileFilter(playFilter);
            save.addChoosableFileFilter(plsFilter);
            save.addChoosableFileFilter(m3u);
            JCheckBox relativePaths = new JCheckBox(rb.getString("CheckBox.RelativePaths"),false);
            save.setAccessory(relativePaths);
            load.setFileFilter(all);
            save.setFileFilter(all);
            //SwingUtilities.invokeLater(new Runnable(){
            //    ConfigData config = ConfigData.getReference();
            //    public void run(){
                    if ( config.getDefaultDirForPlayLists() != null){
                        File file = new File(config.getDefaultDirForPlayLists());
                        if( file.exists() && file.canRead() && file.isDirectory() ){
                            PlayList.this.load.setCurrentDirectory(file);
                            PlayList.this.save.setCurrentDirectory(file);
           }Example of a FileFilter:
    abstract class DefaultFileFilter extends javax.swing.filechooser.FileFilter{
        public String getExtension(){ return ".ppl"; }
    class AllPlaylistsFilter extends DefaultFileFilter{
         public boolean accept(File pathname) {
            if ( pathname.isDirectory() ) return true;
            String name = pathname.getPath();
            int pos = name.lastIndexOf('.');
            String extension = name.substring(pos+1);
            if ( extension.equalsIgnoreCase("m3u") || extension.equalsIgnoreCase("pls") || extension.equalsIgnoreCase("ppl") ) return true;
            return false;
         public String getDescription(){ return "All Playlists"; }
         public String getExtension(){ return ".m3u"; }
    }Cheers Michael

  • JFileChooser.showSaveDialog and Filename field

    I am implementing the actionPerformed method for a "Save As" menu command. In my standard JFileChooser "Save" dialog (showSaveDialog, Metal L&F), I volunteer the current filename (by a previous call to setSelectedFile). The dialog opens just fine. If the user selects a file in the list, the name of the selected file appears in the "File name" textfield as expected. But if the user selects a directory in the list, the name of the directory likewise appears in the "File name" textfield.
    From other programs (including JBuilder4) I am used to having the filename stay put when I select and/or open a directory in a Save Dialog. Is this just the way a JFileChooser save dialog works in the Metal L&F, am I doing something strange, or is there a workaround?
    Thanks very much.
        File tempFile = new File( activePI.getPathname() );
        defaultSaveDir = tempFile.getParentFile();
        JFileChooser chooser = new JFileChooser(defaultSaveDir);
        chooser.setSelectedFile(tempFile);

    Thanks to both of you for the help. I actually came up with the key element of trevorryan1's solution shortly after posting my followup yesterday: consuming any setSelectedFile call when the file argument is a directory. Once this test is in, the counter etc is no longer needed! I consider the JFileChooser's "overwrite the filename textfield" behavior to be a bug, since my !file.isDirectory() override of setSelectedFile shouldn't do anything that setFileSelectionMode(JFileChooser.FILES_ONLY) doesn't already do (FILES_ONLY is the default setting).
    Here is the test class that I posted to the BugParade; I'll post the URL when/if it shows up.
    import java.io.File;
    import javax.swing.JFileChooser;
    class JFileChooserBug
      //Note: comment out the first or second declaration of JFileChooser chooser
      public static void main(String[] args)
        // 1. in a standard JFileChooser save dialog, navigating to another
        // directory will (inappropriately) overwrite the "File name:" textfield.
        // This should not happen when fileSelectionMode = FILES_ONLY (the default).
        JFileChooser chooser = new JFileChooser();
        // 2. in a JFileChooser with a hacked setSelectedFile method, the
        // "File name:" text field is (appropriately) left alone.
        //JFileChooser chooser = new MyJFileChooser();
        //chooser.setFileSelectionMode(JFileChooser.FILES_ONLY);  // = default anyway
        // show the Save dialog with a default file selected
        chooser.setSelectedFile( new File("dummyfile") );
        chooser.showSaveDialog(null);
      public static class MyJFileChooser extends JFileChooser
        //OVERRIDE
        public void setSelectedFile(File file)
          if ( !file.isDirectory() )
            super.setSelectedFile(file);
    }

  • JFileChooser hangs sometimes

    Hi,
    When I open a JFileChooser save dialog the EDT thread hangs indefinitely. From the stack trace I can see that it is waiting indefinitely when it tries to check if a file is a link or not. This happens only sometimes.The default selected directory(My Documents) does not contain any links or shortcuts.
    Following is the stack trace of AWT-EventQueue thread:
    "AWT-EventQueue-2" prio=6 tid=0x039c9400 nid=0x1210 waiting on condition [0x0400e000..0x0400fb94]
    java.lang.Thread.State: WAITING (parking)
         at sun.misc.Unsafe.park(Native Method)
         - parking to wait for <0x0ae38cd0> (a java.util.concurrent.FutureTask$Sync)
         at java.util.concurrent.locks.LockSupport.park(Unknown Source)
         at java.util.concurrent.locks.AbstractQueuedSynchronizer.parkAndCheckInterrupt(Unknown Source)
         at java.util.concurrent.locks.AbstractQueuedSynchronizer.doAcquireSharedInterruptibly(Unknown Source)
         at java.util.concurrent.locks.AbstractQueuedSynchronizer.acquireSharedInterruptibly(Unknown Source)
         at java.util.concurrent.FutureTask$Sync.innerGet(Unknown Source)
         at java.util.concurrent.FutureTask.get(Unknown Source)
         at sun.awt.shell.Win32ShellFolderManager2$ComInvoker.invoke(Unknown Source)
         at sun.awt.shell.Win32ShellFolder2.hasAttribute(Unknown Source)
         at sun.awt.shell.Win32ShellFolder2.isLink(Unknown Source)
         - locked <0x0ae38b00> (a sun.awt.shell.Win32ShellFolder2)
         at javax.swing.filechooser.FileSystemView.isFileSystem(Unknown Source)
         at javax.swing.filechooser.FileSystemView.getSystemDisplayName(Unknown Source)
         at javax.swing.plaf.basic.BasicFileChooserUI$BasicFileView.getName(Unknown Source)
         at javax.swing.JFileChooser.getName(Unknown Source)
         at sun.swing.FilePane$FileRenderer.getListCellRendererComponent(Unknown Source)
         at javax.swing.plaf.basic.BasicListUI.updateLayoutState(Unknown Source)
         at javax.swing.plaf.basic.BasicListUI.maybeUpdateLayoutState(Unknown Source)
         at javax.swing.plaf.basic.BasicListUI.getPreferredSize(Unknown Source)
         at javax.swing.JComponent.getPreferredSize(Unknown Source)
         at javax.swing.ScrollPaneLayout.layoutContainer(Unknown Source)
         at java.awt.Container.layout(Unknown Source)
         at java.awt.Container.doLayout(Unknown Source)
         at java.awt.Container.validateTree(Unknown Source)
         at java.awt.Container.validateTree(Unknown Source)
         at java.awt.Container.validateTree(Unknown Source)
         at java.awt.Container.validateTree(Unknown Source)
         at java.awt.Container.validateTree(Unknown Source)
         at java.awt.Container.validateTree(Unknown Source)
         at java.awt.Container.validateTree(Unknown Source)
         at java.awt.Container.validateTree(Unknown Source)
         at java.awt.Container.validate(Unknown Source)
         - locked <0x0914e040> (a java.awt.Component$AWTTreeLock)
         at java.awt.Dialog.conditionalShow(Unknown Source)
         - locked <0x0914e040> (a java.awt.Component$AWTTreeLock)
         at java.awt.Dialog.show(Unknown Source)
         at javax.swing.JFileChooser.showDialog(Unknown Source)
         at javax.swing.JFileChooser.showSaveDialog(Unknown Source)
         at com.text.SaveApp.launchExportDialog(ActionManager.java:1356)
         at com.text.SaveApp.actionPerformed(ActionManager.java:608)
         at javax.swing.AbstractButton.fireActionPerformed(Unknown Source)
         at javax.swing.AbstractButton$Handler.actionPerformed(Unknown Source)
         at javax.swing.DefaultButtonModel.fireActionPerformed(Unknown Source)
         at javax.swing.DefaultButtonModel.setPressed(Unknown Source)
         at javax.swing.AbstractButton.doClick(Unknown Source)
         at javax.swing.plaf.basic.BasicMenuItemUI.doClick(Unknown Source)
         at javax.swing.plaf.basic.BasicMenuItemUI$Handler.mouseReleased(Unknown Source)
         at java.awt.Component.processMouseEvent(Unknown Source)
         at javax.swing.JComponent.processMouseEvent(Unknown Source)
         at java.awt.Component.processEvent(Unknown Source)
         at java.awt.Container.processEvent(Unknown Source)
         at java.awt.Component.dispatchEventImpl(Unknown Source)
         at java.awt.Container.dispatchEventImpl(Unknown Source)
         at java.awt.Component.dispatchEvent(Unknown Source)
         at java.awt.LightweightDispatcher.retargetMouseEvent(Unknown Source)
         at java.awt.LightweightDispatcher.processMouseEvent(Unknown Source)
         at java.awt.LightweightDispatcher.dispatchEvent(Unknown Source)
         at java.awt.Container.dispatchEventImpl(Unknown Source)
         at java.awt.Window.dispatchEventImpl(Unknown Source)
         at java.awt.Component.dispatchEvent(Unknown Source)
         at java.awt.EventQueue.dispatchEvent(Unknown Source)
         at java.awt.EventDispatchThread.pumpOneEventForFilters(Unknown Source)
         at java.awt.EventDispatchThread.pumpEventsForFilter(Unknown Source)
         at java.awt.EventDispatchThread.pumpEventsForHierarchy(Unknown Source)
         at java.awt.EventDispatchThread.pumpEvents(Unknown Source)
         at java.awt.EventDispatchThread.pumpEvents(Unknown Source)
         at java.awt.EventDispatchThread.run(Unknown Source)
    "Basic L&F File Loading Thread" prio=6 tid=0x03413800 nid=0x1438 waiting on condition [0x0503f000..0x0503fd94]
    java.lang.Thread.State: WAITING (parking)
         at sun.misc.Unsafe.park(Native Method)
         - parking to wait for <0x0ae389c0> (a java.util.concurrent.FutureTask$Sync)
         at java.util.concurrent.locks.LockSupport.park(Unknown Source)
         at java.util.concurrent.locks.AbstractQueuedSynchronizer.parkAndCheckInterrupt(Unknown Source)
         at java.util.concurrent.locks.AbstractQueuedSynchronizer.doAcquireSharedInterruptibly(Unknown Source)
         at java.util.concurrent.locks.AbstractQueuedSynchronizer.acquireSharedInterruptibly(Unknown Source)
         at java.util.concurrent.FutureTask$Sync.innerGet(Unknown Source)
         at java.util.concurrent.FutureTask.get(Unknown Source)
         at sun.awt.shell.Win32ShellFolderManager2$ComInvoker.invoke(Unknown Source)
         at javax.swing.plaf.basic.BasicDirectoryModel$LoadFilesThread.run0(Unknown Source)
         at javax.swing.plaf.basic.BasicDirectoryModel$LoadFilesThread.run(Unknown Source)
    "Swing-Shell" daemon prio=6 tid=0x03b8e800 nid=0x7e4 waiting for monitor entry [0x0437f000..0x0437fb14]
    java.lang.Thread.State: BLOCKED (on object monitor)
         at sun.awt.shell.Win32ShellFolder2.isFileSystem(Unknown Source)
         - waiting to lock <0x0ae38b00> (a sun.awt.shell.Win32ShellFolder2)
         at sun.awt.shell.Win32ShellFolder2.equals(Unknown Source)
         at java.util.AbstractList.equals(Unknown Source)
         at java.util.Vector.equals(Unknown Source)
         - locked <0x0ae38b90> (a java.util.Vector)
         at javax.swing.plaf.basic.BasicDirectoryModel$LoadFilesThread$1.call(Unknown Source)
         at javax.swing.plaf.basic.BasicDirectoryModel$LoadFilesThread$1.call(Unknown Source)
         at java.util.concurrent.FutureTask$Sync.innerRun(Unknown Source)
         at java.util.concurrent.FutureTask.run(Unknown Source)
         at java.util.concurrent.ThreadPoolExecutor$Worker.runTask(Unknown Source)
         at java.util.concurrent.ThreadPoolExecutor$Worker.run(Unknown Source)
         at sun.awt.shell.Win32ShellFolderManager2$ComInvoker$3.run(Unknown Source)
         at java.lang.Thread.run(Unknown Source)
    Let me know if any one has faced similar problems.

    "AWT-EventQueue-2"
    - locked <0x0ae38b00> (a sun.awt.shell.Win32ShellFolder2)
    "Swing-Shell"
    - waiting to lock <0x0ae38b00> (a sun.awt.shell.Win32ShellFolder2)
    That's definitely a symptom of the problem. AWT-EventQueue-2 has not released that lock because it is:
    - parking to wait for <0x0ae38cd0> (a java.util.concurrent.FutureTask$Sync)
    Can you find that object "0x0ae38cd0" somewhere else in the thread dump? It might be revealing to see who has ahold of it and why they haven't released it yet.

  • JFileChooser over internet

    Hello,
    Is there a way for JFileChooser to access a content repository through the internet. For example, I'm using JFileChooser save dialog to allow the user to upload files to my content repository, but I can't seem to set the directory to my repository. I've tried creating a URI pointing to the repository passing that into a file and setting the JFileChooser's current directory but that doesn' t seem to work. If JFileChooser can't do this, is there another UI similar to JFileChooser I can use. Any help is much appreciated.
    vpyang

    I'll assume you've made your directories brousable so you can get a listing of files... you could use a dropdown and just load it off of the list you get... If you select a folder, then enter that folder and repopulate accordingly.Or, instead of a dropdown, you can create a subclass of FileSystemView, and basically add extensions to the default FileSystemView - then plug that into JFileChooser

  • My JAR file is not working properly!!!

    Hi everyone,
    I made an application that has a GUI (window). I converted it into a JAR file so I can send it to a friend by email. Then she can run it to generate the output. First, the user has to select a destination to save the .txt file (using JFileChooser). Then enters the inputs (using JTextFields). Clicks "Run" button (Results will be calculated and copied to the file). A Message will appear indicating that the results are copied. The problem is that when I run the application in the IDE (Eclipse) it works fine. But when I convert it into JAR, The moment I click the "Run" button, suddenly the window closes. Please HELP???
    Thank you

    DrClap wrote:
    Eng.Sh_2004 wrote:
    Sorry guys, but i would like to make things clearer, As I mentioned earlier, What i'm doing is the following: 1) Using the Jfilechooser, save the results into a filename.txt file _[main class in the manifest file (class for the GUI) ]._ 2) Click "run" to write the data to the created file in step 1 [_another class is used to write to file_]. I have a feeling that the problem is related to the manifest main class. What do you think guys?I think your description of the problem is very bad. And I think your idea of making wild guesses is a bad way of diagnosing problems.
    First of all. A JFileChooser does not save anything. It just allows the user to select a file to be saved to. So if you thought that the first step was writing anything or creating any file, you're probably wrong. But examining the code would help you understand.
    Second, if you're having problems because one class chooses the file name and a second class writes data to it, then you're probably running into the basic beginner problem we see around here all the time of how to communicate data between objects. Again, examining the code might help.
    Third, you need to understand what is writing that error message. Examining the code would help there too.
    So: stop guessing. Look at the code.I'm still New To Java that's why i find difficulty in problems diagnosis. Regarding the JAR problem, as you mentioned, I used JFileChooser to select a file and (copying data) is the other part. So I will look at the code again.
    Edited by: Eng.Sh_2004 on Aug 26, 2010 1:10 PM

  • Event handling from class to another

    i get toolbarDemo.java which make event handling to JTextArea in the same class
    http://java.sun.com/docs/books/tutorial/uiswing/components/example-1dot4/index.html#ToolBarDemo
    but i have another class and i make object of toolBar class and i move toolBar icons only how can i move the event handling as open ,save,copy,paste to my another class
    i want to ignore actionPerformed of toolBar class and listen to my another's class actionPerformed
    thanks

    Rather than trying to use the ToolBarDemo class as-is you can use/modify the methods in it for your own class, like this:
    import java.awt.*;
    import java.awt.event.*;
    import java.net.URL;
    import javax.swing.*;
    import javax.swing.text.TextAction;
    public class ToolBarIconTest implements ActionListener
        static final private String OPEN  = "open";
        static final private String SAVE  = "save";
        static final private String COPY  = "copy";
        static final private String PASTE = "paste";
        public void actionPerformed(ActionEvent e)
            String cmd = e.getActionCommand();
            if (OPEN.equals(cmd))
                System.out.println("show a JFileChooser open dialog");
            if (SAVE.equals(cmd))
                System.out.println("show a JFileChooser save dialog");
        private JToolBar getToolBar()
            JToolBar toolBar = new JToolBar();
            addButtons(toolBar);
            return toolBar;
        protected void addButtons(JToolBar toolBar) {
            JButton button = null;
            //first button
            button = makeGeneralButton("Open24", OPEN,
                                       "To open a document",
                                       "Open", this);
            toolBar.add(button);
            //second button
            button = makeGeneralButton("Save24", SAVE,
                                       "To save a document",
                                       "Save", this);
            toolBar.add(button);
            //third button
            button = makeGeneralButton("Copy24", COPY,
                                       "Copy from focused text component",
                                       "Copy", copy);
            toolBar.add(button);
            //fourth button
            button = makeGeneralButton("Paste24", PASTE,
                                       "Paste to the focused text component",
                                       "Paste", paste);
            toolBar.add(button);
        protected JButton makeGeneralButton(String imageName,
                                            String actionCommand,
                                            String toolTipText,
                                            String altText,
                                            ActionListener l) {
            //Look for the image.
            String imgLocation = "toolbarButtonGraphics/general/"
                                 + imageName
                                 + ".gif";
            URL imageURL = ToolBarIconTest.class.getResource(imgLocation);
            //Create and initialize the button.
            JButton button = new JButton();
            button.setActionCommand(actionCommand);
            button.setToolTipText(toolTipText);
            button.addActionListener(l);
            if (imageURL != null) {                      //image found
                button.setIcon(new ImageIcon(imageURL, altText));
            } else {                                     //no image found
                button.setText(altText);
                System.err.println("Resource not found: "
                                   + imgLocation);
            return button;
        private Action copy = new TextAction(COPY)
            public void actionPerformed(ActionEvent e)
                JTextComponent tc = getFocusedComponent();
                int start = tc.getSelectionStart();
                int end = tc.getSelectionEnd();
                if(start == end)
                    tc.selectAll();
                tc.copy();
        private Action paste = new TextAction(PASTE)
            public void actionPerformed(ActionEvent e)
                getFocusedComponent().paste();
        private JPanel getTextFields()
            JPanel panel = new JPanel(new BorderLayout());
            panel.add(new JTextField(12), "North");
            panel.add(new JTextField(12), "South");
            return panel;
        public static void main(String[] args)
            ToolBarIconTest test = new ToolBarIconTest();
            JFrame f = new JFrame();
            f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
            f.getContentPane().add(test.getToolBar(), "North");
            f.getContentPane().add(test.getTextFields());
            f.setSize(360,240);
            f.setLocation(200,200);
            f.setVisible(true);
    }Use the -cp option as shown in the ToolBarDemo class comments
    C:\jexp>java -cp .;path_to_jar_file/jlfgr-1_0.jar ToolBarIconTest

  • FileDialog Creation

    Can somebody pls show mi how to create the FileDialog for saving a file ??
    i have alrady create the Dialog alrady......
    it juz that it couldn't save the file that i want.....
    I am new to Java Programming... so hope that i can ask for your help...
    Thanks

    just the basics
    <code>
    JFileChooser saver = new JFileChooser();
    int val = saver.showSaveDialog(this);
    if (val == JFileChooser.APPROVE_OPTION)
    //assume an already created File variable file
    file = saver.getSelectedFile();
    else
    return;
    // save the file to hard drive
    try {//assume you have some text area named editor
    editor.write( new BufferedWriter( new FileWriter(file) ) );
    catch (IOException ioe) {
    ioe.printStackTrace();
    </code>
    That should get you started anyway

  • How to save a file in Jfilechooser with extension

    hi all
    i'm trying to save a file with a certain extension
    i have my class that extends FileFilter, and which write into the jfilechooser combo box with extensions. .jar
    how can i save a file with this extension?
    here is the code
    JFileChooser fileChooser = new JFileChooser();
              fileChooser.addChoosableFileFilter(new JarFilter());
              int returnVal = fileChooser.showDialog(new JFrame(), "Export");
              if (returnVal == JFileChooser.APPROVE_OPTION) {
                   File file = fileChooser.getSelectedFile();
                   try {
                        JarExporter exporter=new JarExporter(this.generateXMLString(file.getName().replaceAll(".jar", "")),
                                       this.editor.getLinkageCanvas().getSelectedWidgetIDs());
                        exporter.exportJarFile(file);
                   } catch (Exception exception) {
                        System.out.println("Export error.");
              }

    hi all
    i'm trying to save a file with a certain extension
    i have my class that extends FileFilter, and which write into the jfilechooser combo box with extensions. .jar
    how can i save a file with this extension?
    here is the code
    JFileChooser fileChooser = new JFileChooser();
              fileChooser.addChoosableFileFilter(new JarFilter());
              int returnVal = fileChooser.showDialog(new JFrame(), "Export");
              if (returnVal == JFileChooser.APPROVE_OPTION) {
                   File file = fileChooser.getSelectedFile();
                   try {
                        JarExporter exporter=new JarExporter(this.generateXMLString(file.getName().replaceAll(".jar", "")),
                                       this.editor.getLinkageCanvas().getSelectedWidgetIDs());
                        exporter.exportJarFile(file);
                   } catch (Exception exception) {
                        System.out.println("Export error.");
              }

Maybe you are looking for

  • Processo de importação - NF-e de entrada

    Olá pessoal, Alguém poderia me ajudar com dicas de como proceder para implementar o processo de importação utilizando nota fiscal eletrônica para a entrada das mercadorias? Atualmente, o nosso despachante emite a NF de entrada referente a importação

  • "file not found" error in VI Logger when running an imported VI Logger task

    I'm having trouble getting all of my imported tasks to run in VI Logger. I'm using VI Logger 2.0, with an SCXI-1100.  The data acquisition tasks I import run fine.  One of the VI Logger tasks I've imported runs OK, but the other one gives an error: "

  • Maximum file size for CV in E-recruitment

    hi, my name is chandra. i would like to know ' how we can restrict maximum file size of CV' in the E-recruitment module? By the i am working on E-recruitment support project at the moment. can some one reply me quickly? thanks regards chandra

  • Recommended way to start db on oracle10g asm in cluster

    We have a oracle 10g asm instance running on Solaris 10 cluster. During maintenance activity, we shutdown the database using cluster but startup of the database is carried out by DBA & not thru cluster. We then start the cluster service of the databa

  • Moving Scriptlet Code to backing bean when converting from JSP - Facelets

    Hello! We are converting our application from jsf1.2 to 2.0 and all jsps are being converted to XHTML. Some are trivial while others had very complex scriptlets. I would like to know what are some of the recommended ways of moving Scriptlet Code to b