Error in JFileChooser

hi, i created a fileChooser but im getting the error: java.lang.StackOverflowError
what can i do?
thanks
JFileChooser fc=new JFileChooser(){
public void approveSelection()
{    File f = getSelectedFile();
if (f.exists() && f.isFile() && f.getName().endsWith(".dat"))
JOptionPane.showMessageDialog(null, "Wrong file","File not Writable",JOptionPane.ERROR_MESSAGE);
return;
fc.approveSelection();
fc.addChoosableFileFilter(new simpleFileFilter());
fc.setFileFilter(new simpleFileFilter());
fc.setFileSelectionMode(JFileChooser.FILES_AND_DIRECTORIES);
fc.setCurrentDirectory(new File(" C: /Documents and Settings"));
fc.setAcceptAllFileFilterUsed(true);
int returnVal=fc.showOpenDialog(null);
class simpleFileFilter extends javax.swing.filechooser.FileFilter
public boolean accept (File f) {
String name=f.getName().toLowerCase();
if (name.endsWith(".dat")) return true;
return false;
public String getDescription() {return "*.dat";}
}

  JFileChooser fc=new JFileChooser()
    public void approveSelection()
      File f = getSelectedFile();
      if (f.exists() && f.isFile() && f.getName().endsWith(".dat"))
        JOptionPane.showMessageDialog(null, "Wrong file","File not Writable",JOptionPane.ERROR_MESSAGE);
        return;
      fc.approveSelection(); //Infinite loop caused here.  Try using super.approveSelection();
  };

Similar Messages

  • No Disk Error when opening JFileChooser

    Hi all
    After launching my app via JWS and opening my apps FileChooser I get a 'javaw.exe - No Disk' error message:
    'There is no disk in the drive. Please insert a disk into drive A:.'
    This doesn't happen if I start the app without JWS. Although it happens only the first time after opening the FileChooser it's rather annoying for the user. I can't expect the user always having a disk in their drive.
    Is there a way of switching the scan for drive A off?
    Thanks for your help.
    Stephan

    See Top 25 Bugparade: # 4264750
    This is a SecurityManager - Problem and the java.io.File.
    eg.:
    System.setSecurityManager(new RMISecurityManager());
    File[] roots = File.listRoots();
    Then you will see the problem...
    I tried the following workaround:
    before you access disk. (or JFileChooser)
    SecurityManager sm = System.getSecurityManger();
    System.setSecurityManager(null);
    // disable the SecurityManger
    // this special disk access needs no SecurityManager..
    ... popup JFileChosser or make FileAccess..
    System.setSecurityManager(sm);
    // restore the old SecurityManger
    It's not the best solution but it works..
    hope this will help,
    Wolfgang
    EDI Organisation

  • JFileChooser strange registry error

    I am testing a java application on windows 7 and just saw a very strange error pop up after trying to use a JFileChooser:
    An error was detected in the windows registry.
    Required windows folders were missing.
    Googling this did not turn up anything obvious.
    Clicking OK then showed:
    Some local folders are missing.
    Missing: C:\programdata\OEM Links
    Full folder List:
    C:\Users\Public\Desktop
    ... (other folders)
    Anyone ever seen anything like this before?
    Or anyone have an idea what might be going on?
    This is a fresh win7 install on a test box (ghosted for re-imaging)
    why does JFileChooser care about the registry?

    Hello,
    I'm sorry you haven't got a reply so far. Here are some considerations, that you can now wish to consider:
    I am testing a java application on windows 7 and just saw a very strange error pop up after trying to use a JFileChooser:Can you test it on another version of Windows? What is the result?
    If you don't have any other Windows version available, can you post an SSCCE (a 10-line program that tries to open a JFileChooser, and reproduces the problem), so that you, me, and other people, have a chance to run the exact same test on various OS?
    In all cases, you always have more chance to receive an answer when you post an SSCCE that demonstrates the problem with convenience for other forum users: http://sscce.org
    An error was detected in the windows registry.
    Required windows folders were missing.
    Googling this did not turn up anything obvious.Googling "JFIleChooser registry" did turn up a few interesting links, see below.
    Some local folders are missing.
    Missing:  C:\programdata\OEM Links
    Full folder List: 
    C:\Users\Public\Desktop
    ...   (other folders)Anyone ever seen anything like this before?
    Or anyone have an idea what might be going on?From the looks of it, it seems the JRE is using the registry to have some info about the files system. I don't know for sure which info and why, but I don't find that so surprising (admittedly, the error message itself is rather unclear).
    why does JFileChooser care about the registry?Not the registry itself, but merely the info it contains about the filesystem's structure. I imagine drive names and mapping of network drives can be found there, for example.
    As claimed above, Googling led me to the following bug entries:
    http://bugs.sun.com/bugdatabase/view_bug.do?bug_id=4879395
    http://bugs.sun.com/bugdatabase/view_bug.do?bug_id=4712307
    Don't necessarily traverse the whole contents of the bug entries themselves: the point is that they prove that the JRE is indeed leveraging filesystem info from the registry (the reason was, if I understand correctly, to improve performance in the case of network drives, and in the case of very numerous files).
    The other point is that both bug entries describe the same command-line flag to disable at least one mechanism that leverages the registry:
    java -Dswing.disableFileChooserSpeedFix ...Hopefully, that may, with no guarantee, fix your specific issue. Try it and let us know.
    Best regards,
    J.

  • Error compiling with JFileChooser

    Hi all,
    I'm having a problem with some code not compiling. I'm using the linux blackdown sdk on FreeBSD. I have created a new class to test this problem and I get the same response I was getting in my main application. The code is as follows:
    import javax.swing.*;
    import java.awt.*;
    import java.awt.event.*;
    public class Test extends JFrame {
            JFileChooser chooser = new JFileChooser(".");
            chooser.setFileSelectionMode(JFileChooser.DIRECTORIES_ONLY);
    }The error message that I am getting is as follows:
    $ javac Test.java
    Test.java:9: <identifier> expected
    chooser.setFileSelectionMode(JFileChooser.DIRECTORIES_ONLY);
    ^
    Test.java:9: package chooser does not exist
    chooser.setFileSelectionMode(JFileChooser.DIRECTORIES_ONLY);
    ^
    2 errors
    I can't see what I'm doing wrong here. I've definitely created chooser as a new JFileChooser object.
    Any help would be much appreciated!
    Thanks,

    you can't call one of your object's methods outside of a method/constructor body. Try this:
    import javax.swing.*;
    import java.awt.*;
    import java.awt.event.*;
    public class Test extends JFrame {
         JFileChooser chooser;
         public Test() {
              super("Test");
              chooser = new JFileChooser(".");
              chooser.setFileSelectionMode(JFileChooser.DIRECTORIES_ONLY);
    Happy Birthday to Me.

  • JFileChooser permission error.

    Our application, or applet if you will has been working fine. We have not needed to create any specific security permissions on the client PC as the applet is signed.
    As of late, and only in IE we get a:
    java.security.AccessControlException: access denied (java.util.PropertyPermission user.dir read)
    When the code below is executed.
    int returnVal = selectOMission.showDialog(this, "Save Mission");
    --selectOMission is defined as "JFileChooser selectOMission = new JFileChooser();"
    This problem is not present in linux, or when running other browsers in XP.
    Anyone have any ideas?

    Self healing is good.
    We keep out look and feel in a separate jar. Makes it easier to customize the app. The error was not being caused by the FileChooser but rather by the ui.
    Signing the look jar fixed it.
    It is rather strange that this only occurred when using IE on windows all other browsers worked and EI on Mac worked as well ...

  • JFileChooser - No Disk In Drive Error

    heres the code I have used for three other applications. For some reason the current project I am working on, no matter what button I attach the below to, seems to display a "No disk in Drive. Please insert a disk into drive A" error. The fact that this code seems to work in 3 other apps on the same win2000 box, and a test program I wrote that just made a JFrame and put a button on it with the below code worked, has me boggled.
    someButton.addActionListener(new ActionListener()
         public void actionPerformed(ActionEvent evt)
              JFileChooser fc = new JFileChooser();
         int val = fc.showOpenDialog(null);
         if(val == javax.swing.JFileChooser.APPROVE_OPTION)
         java.io.File fileChoosen = fc.getSelectedFile();
         System.out.println(fileChoosen.getAbsolutePath());
    and yes, I have tried JFileChooser("SomeDirectory"). I have tried all other workarounds posted about this known issue and none of them work. WHY would this code decide not to work in my new project but works on three other and a test app. heres the test app the above code worked in:
    public class Main
         File fileChoosen;
         public static void main(String[] args)
              new Main();
         public Main()
              JFrame f = new JFrame();
              JButton getFile = new JButton("get file");
              getFile.addActionListener(new ActionListener()
                   public void actionPerformed(ActionEvent evt)
                        JFileChooser fc = new JFileChooser();
                   int val = fc.showOpenDialog(null);
                   if(val == JFileChooser.APPROVE_OPTION)
                   fileChoosen = fc.getSelectedFile();
                   System.out.println(fileChoosen.getAbsolutePath());
              f.getContentPane().add(getFile);
              f.setSize(100,100);
              f.show();
    i have tried this code in about 5 different places in the new application and it always pops this drive not ready error box. can't seem to break it in any other apps i have written or the above Main.java.
    Does Anyone know what would cause this. The App it does not work in uses alot of polymorphism, rmi, and interfaces. could something weird be happening? the other apps are more straight foward one JFrame apps with FileMenu's, and tabs. mostly config windows. this one is much larger with many JFrames and is completly dependent on a server. so a client networked app.

    Linda Radecke posted a workaround in the comp.lang.java.gui newsgroup recently. Here's the relevant part of her post:
    ...this is known bug in JFileChooser on some JDK/machine-combis. (Do you have a CD-ROM-drive?). I myself don't have this problem, but I have read about it, there is a workaround I have copied to my website once, maybe this can help you, I haven't tried that out myself, since everything works well for me with respect to JFileChooser:
    http://www.jalice.net/windowsAltFileSystemView.java.html
    I have included the code from the above link here, in case it ever disappears. Note that I haven't tried this myself, but I've been so frustrated at the lack of a workaround, I thought it was a good idea to post it for future reference:
    import javax.swing.filechooser.*;
    import java.io.*;
    import java.util.*;
    import java.lang.reflect.Method;
    /* Keep your current code, but use a customized FileSystemView
       that you supply to JFileChooser when instantiating it on
       Windows. e.g. :
       new JFileChooser(currentDirectory, new WindowsAltFileSystemView())
    class WindowsAltFileSystemView extends FileSystemView {
        private static final Object[] noArgs                 = {};
        private static final Class[]  noArgTypes             = {};
        private static Method         listRootsMethod        = null;
        private static boolean        listRootsMethodChecked = false;
        * Returns true if the given file is a root.
        public boolean isRoot(File f) {
            if (!f.isAbsolute()) {
                return false;
            String parentPath = f.getParent();
            if (parentPath == null) {
                return true;
            } else {
                File parent = new File(parentPath);
                return parent.equals(f);
        * creates a new folder with a default folder name.
        public File createNewFolder(File containingDir) throws IOException {
            if (containingDir == null) {
                throw new IOException(
                    "Containing directory is  null:");
            File newFolder = null;
            // Using NT's default folder name
            newFolder = createFileObject(containingDir,"New Folder");
            int i = 2;
            while (newFolder.exists() && (i < 100)) {
                newFolder = createFileObject(containingDir,
                                             "New Folder ("+ i + ")");
                i++;
            if (newFolder.exists()) {
                throw new IOException(
                    "Directory already                      exists:"
                    + newFolder.getAbsolutePath());
            } else {
                newFolder.mkdirs();
            return newFolder;
        * Returns whether a file is hidden or not. On Windows
        * there is currently no way to get this information from
        * io.File, therefore always return false.
        public boolean isHiddenFile(File f) {
            return false;
        * Returns all root partitians on this system. On
        Windows, this
        * will be the A: through Z: drives.
        public File[] getRoots() {
            Vector rootsVector = new Vector();
            // Create the A: drive whether it is mounted or not
            FileSystemRoot floppy = new FileSystemRoot("A" + ":" + "\\");
            rootsVector.addElement(floppy);
            // Run through all possible mount points and check
            // for their existance.
            for (char c = 'C'; c <= 'Z'; c++) {
                char   device[]   = { c, ':', '\\' };
                String deviceName = new String(device);
                File   deviceFile = new FileSystemRoot(deviceName);
                if ((deviceFile != null) && deviceFile.exists()) {
                    rootsVector.addElement(deviceFile);
            File[] roots = new File[rootsVector.size()];
            rootsVector.copyInto(roots);
            return roots;
            // return null;
        class FileSystemRoot extends File {
            public FileSystemRoot(File f) {
                super(f, "");
            public FileSystemRoot(String s) {
                super(s);
            public boolean isDirectory() {
                return true;
    /*--- Formatted in Sun Java Convention Style on Thu, Jun 21, '01 ---*/
    /*------ Formatted by Jindent 3.23 Gold 1.02 --- http://www.jindent.de ------*/

  • JFileChooser causes "java.exe - Application Error"

    Hi,
    When I'm closing an JFileChooser dialog (by e.g. pressing ok or cancel) a second or so later my JVM terminates with the error message "java.exe - Application Error. The instruction at "0*6d0ea46e" referenced a memory at "0x00000000". The memory could not be "read". Click on OK to treminate the program".
    I turned on verbose output from the JVM and the last printout was:
    [Loaded javax.swing.Autoscroller from C:\Program Files\Java\jdk1.5.0\jre\lib\rt.jar]
    [Dynamic-linking native method sun.awt.windows.WComponentPeer.removeNativeDropTarget ... JNI]
    result 1
    [Dynamic-linking native method sun.awt.windows.WFramePeer.getState ... JNI]
    [Loaded java.awt.EventDispatchThread$StopDispatchEvent from C:\Program Files\Java\jdk1.5.0\jre\lib\rt.jar]
    [Dynamic-linking native method sun.awt.windows.WToolkit.shutdown ... JNI]
    No exception is shown.
    I have uninstall all old JVMs and reinstalled JDK 5.0. This does not help.
    This simple program causes the termination of the JVM:
    public static void main(String[] args) {
    System.out.println("0");
    JFileChooser fileChooser = new JFileChooser();
    System.out.println("1");
    int result = -2;
    try {
    result = fileChooser.showOpenDialog(null);
    } catch (HeadlessException e1) {
    e1.printStackTrace();
    System.out.println("result " + result);
    try {
    Thread.sleep(5000);
    } catch (InterruptedException e) {
    // TODO Auto-generated catch block
    e.printStackTrace();
    System.out.println("2");
    I receive the printout "result" but not "2".
    I appriciate any help!
    BR
    /Marcus

    No, this is very bad. Any time you see a message like this mentioning a memory address, it means that java, not you, has crashed. There's no way for you to fix this. The only thing you can try is to work around it.
    My suggestions:
    1. Report it to Sun. Make sure you include your system info (processor, memory, computer manufacturer) and what version of java you're using
    2. Try downloading and installing a different version of java

  • JFileChooser error message

    Currently I am facing problem on JFileChosser error message, while user choose on A drive and there is no disk in the drive. So by right the JFileChooser should prompt out a error message or catch exception, BUT ...it do nothing.
    I don't know it is bugs for this JFileChooser, or there is
    actually a method to handle it.
    So please help me on this matter. Thanks in advance.

    It looks like there is a bug filed about this on BugParade - #4307597.

  • JFileChooser error

    does anyone know why I am getting this error when i try to bring up a JFileChooser from a button push?
    Error:
    java(14966,0x18d3600) malloc: *** error for object 0x3ac020: incorrect checksum for freed object - object was probably modified after being freed, break at szone_error to debug
    java(14966,0x18d3600) malloc: *** set a breakpoint in szone_error to debug
    Bus error
    Code:
         public void actionPerformed(ActionEvent event) {
              JFileChooser chooser = new JFileChooser();
              chooser.setCurrentDirectory(new File("."));
              int result = chooser.showOpenDialog(frame);
              if(result == JFileChooser.APPROVE_OPTION) {
                   try {
                        frame.clearTextArea();
                        File f = chooser.getSelectedFile();
                        String[] fData = FileProcessor.readData(f);
                        frame.setCurrentFile(f);
                        frame.appendTextArea(fData);
                   catch(IOException e) {
                        String message = "Check the file and try again";
                        String title = "File Processing Error";
                        JOptionPane.showMessageDialog(frame, message, title, JOptionPane.ERROR_MESSAGE);
    This only seems to happen on OS X (10.4.2) and Fedora Core 4 Linux but not on an XP box.
    Any help would be great.

    It looks like there is a bug filed about this on BugParade - #4307597.

  • JFileChooser Approve Button Error check

    Hi. I am trying to test my save button on my JFilechooser. How do you check to see if the user has inputed anything in filename text field? I have tried the following:
    if (thefile == null || thefile.getName().equals(" "))
         Frame theframe = new Frame();
         JOptionPane.showMessageDialog(theframe, "Invalid file name. ", "Error", JOptionPane.ERROR_MESSAGE);
    }

    What is the error that you are getting? One work around is that you can simply go ahead and try to do a file operation using theFile.. all you need to do is enclose it in a try catch block and catch the exception. Once an exception is thrown, that is where you can write you error reporting code..
    hth

  • NO Disk error when DAQmx is referenced

    Referencing NationalInstruments.DAQmx causes a NO DISK error in Visual Studio (see attachment)
    I'm using Visual Studio 2012 and MS 2013
    The DAqmx version is 9.8.45.42
    Has anyone seen this before and is there a fix?
    Steve
    Attachments:
    DAQMX Error.JPG ‏22 KB

    See Top 25 Bugparade: # 4264750
    This is a SecurityManager - Problem and the java.io.File.
    eg.:
    System.setSecurityManager(new RMISecurityManager());
    File[] roots = File.listRoots();
    Then you will see the problem...
    I tried the following workaround:
    before you access disk. (or JFileChooser)
    SecurityManager sm = System.getSecurityManger();
    System.setSecurityManager(null);
    // disable the SecurityManger
    // this special disk access needs no SecurityManager..
    ... popup JFileChosser or make FileAccess..
    System.setSecurityManager(sm);
    // restore the old SecurityManger
    It's not the best solution but it works..
    hope this will help,
    Wolfgang
    EDI Organisation

  • Infinite loop error after using Java Sun Tutorial for Learning Swing

    I have been attempting to create a GUI following Sun's learning swing by example (example two): http://java.sun.com/docs/books/tutorial/uiswing/learn/example2.html
    In particular, the following lines were used almost word-for-word to avoid a non-static method call problem:
    SwingApplication app = new SwingApplication();
    Component contents = app.createComponents();
    frame.getContentPane().add(contents, BorderLayout.CENTER);I believe that I am accidentally creating a new instance of the gui class repeatedly (since it shows new GUI's constantly and then crashes my computer), possibly because I am creating an instance in the main class, but creating another instance in the GUI itself. I am not sure how to avoid this, given that the tutorials I have seen do not deal with having a main class as well as the GUI. I have googled (a nice new verb) this problem and have been through the rest of the swing by example tutorials, although I am sure I am simply missing a website that details this problem. Any pointers on websites to study to avoid this problem would be appreciated.
    Thanks for your time-
    Danielle
    /** GUI for MicroMerger program
    * Created July/06 at IARC
    *@ author Danielle
    package micromerger;
    import javax.swing.*;
    import java.awt.*;
    import java.awt.event.*;
    import java.io.BufferedWriter;
    import java.io.File;
    import java.io.FileWriter;
    import java.io.IOException;
    import java.io.PrintWriter;
    import javax.swing.JFileChooser;
    import java.lang.Object;
    public class MGui
         private static File inputFile1, inputFile2;
         private static File sfile1, sfile2;
         private static String file1Name, file2Name;
         private String currFile1, currFile2;
         private JButton enterFile1, enterFile2;
         private JLabel enterLabel1, enterLabel2;
         private static MGui app;
         public MGui()
              javax.swing.SwingUtilities.invokeLater(new Runnable()
                   public void run()
                        System.out.println("About to run create GUI method");
                        app = new MGui();
                        System.out.println("declared a new MGui....");
                        createAndShowGUI();
         //initialize look and feel of program
         private static void initLookAndFeel() {
            String lookAndFeel = null;
         lookAndFeel = UIManager.getSystemLookAndFeelClassName();
         try
              UIManager.setLookAndFeel(lookAndFeel);
         catch (ClassNotFoundException e) {
                    System.err.println("Couldn't find class for specified look and feel:"
                                       + lookAndFeel);
                    System.err.println("Did you include the L&F library in the class path?");
                    System.err.println("Using the default look and feel.");
                } catch (UnsupportedLookAndFeelException e) {
                    System.err.println("Can't use the specified look and feel ("
                                       + lookAndFeel
                                       + ") on this platform.");
                    System.err.println("Using the default look and feel.");
                } catch (Exception e) {
                    System.err.println("Couldn't get specified look and feel ("
                                       + lookAndFeel
                                       + "), for some reason.");
                    System.err.println("Using the default look and feel.");
                    e.printStackTrace();
         // Make Components--
         private Component createLeftComponents()
              // Make panel-- grid layout
         JPanel pane = new JPanel(new GridLayout(0,1));
            //Add label
            JLabel welcomeLabel = new JLabel("Welcome to MicroMerger.  Please Enter your files.");
            pane.add(welcomeLabel);
         //Add buttons to enter files:
         enterFile1 = new JButton("Please click to enter the first file.");
         enterFile1.addActionListener(new enterFile1Action());
         pane.add(enterFile1);
         enterLabel1 = new JLabel("");
         pane.add(enterLabel1);
         enterFile2 = new JButton("Please click to enter the second file.");
         enterFile2.addActionListener(new enterFile2Action());
         pane.add(enterFile2);
         enterLabel2 = new JLabel("");
         pane.add(enterLabel2);
         return pane;
         /** Make GUI:
         private static void createAndShowGUI()
         System.out.println("Creating a gui...");
            JFrame.setDefaultLookAndFeelDecorated(true);
            //Create and set up the window.
            JFrame frame = new JFrame("MicroMerger");
            frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
         //Add stuff to the frame
         //MGui app = new MGui();
         Component leftContents = app.createLeftComponents();
         frame.getContentPane().add(leftContents, BorderLayout.WEST);
            //Display the window.
            frame.pack();
            frame.setVisible(true);
    private class enterFile1Action implements ActionListener
         public void actionPerformed(ActionEvent evt)
              JFileChooser chooser = new JFileChooser();
              int rVal = chooser.showOpenDialog(enterFile1);
              if(rVal == JFileChooser.APPROVE_OPTION)
                   inputFile1 = chooser.getSelectedFile();
                   PrintWriter outputStream;
                   file1Name = inputFile1.getName();
                   enterLabel1.setText(file1Name);
    private class enterFile2Action implements ActionListener
         public void actionPerformed(ActionEvent evt)
              JFileChooser chooser = new JFileChooser();
              int rVal = chooser.showOpenDialog(enterFile1);
              if(rVal == JFileChooser.APPROVE_OPTION)
                   inputFile2 = chooser.getSelectedFile();
                   PrintWriter outputStream;
                   file2Name = inputFile2.getName();
                   enterLabel2.setText(file2Name);
    } // end classAnd now the main class:
    * Main.java
    * Created on June 13, 2006, 2:29 PM
    * @author Danielle
    package micromerger;
    import java.awt.*;
    import java.awt.event.*;
    import javax.swing.*;
    import java.io.*;
    public class Main
        /** Creates a new instance of Main */
        public Main()
         * @param args the command line arguments
        public static void main(String[] args)
            MGui mainScreen = new MGui();
            //mainScreen.setVisible(true);
            /**Starting to get file choices and moving them into GPR Handler:
             System.out.println("into main method");
         String file1Name = new String("");
             file1Name = MGui.get1Name();
         System.out.println("good so far- have MGui.get1Name()");
        }// end main(String[] args)
    }// end class Main

    um, yeah, you definitely have a recursion problem, that's going to create an infinite loop. you will eventually end up an out of memory error, if you don't first get the OS telling you you have too many windows. interestingly, because you are deferring execution, you won't get a stack overflow error, which you expect in an infinite recursion.
    lets examine why this is happening:
    in main, you call new MGui().
    new MGui() creates a runnable object which will be run on the event dispatch thread. That method ALSO calls new MGui(), which in turn ALSO creates a new object which will be run on the event dispatch thead. That obejct ALSO calls new MGui(), which ...
    well, hopefully you get the picture.
    you should never unconditionally call a method from within itself. that code that you have put in the constructor for MGui should REALLY be in the main method, and the first time you create the MGui in the main method as it currently exists is unnecessary.
    here's what you do: get rid of the MGui constructor altogether. since it is the implicit constructor anyway, if it doesn't do anything, you don't need to provide it.
    now, your main method should actually look like this:
    public static void main( String [] args ) {
      SwingUtilities.invokeLater( new Runnable() {
        public void run() {
          MGui app = new MGui();
          app.createAndShowGUI();
    }// end mainyou could also declare app and call the constructor before creating the Runnable, as many prefer, because you would have access to it from outside of the Runnable object. The catch there, though, is that app would need to be declared final.
    - Adam

  • How can I get an extension from a file...in JFileChooser

    I have got a problem here. Here I have a JFileChooser, I want to add in
    a FileFilter, and user could only see some type of file. But as long as I
    try to get the extension....It wont compile, could any one teach me how
    to get the extension of a file in JFILECHOOSER???
    ============================================
    import java.io.*;
    import java.io.File.*;
    import javax.swing.filechooser.FileFilter;
    public class MainFrame extends JFrame implements ActionListener {
    public MainFrame() {.............}
    private boolean chooseFile()
    JFileChooser fileChooser = new JFileChooser();
    fileChooser.setFileSelectionMode( JFileChooser.FILES_ONLY );
    FileChoser filtering = new FileChoser("txt");
    fileChooser.setFileFilter(filtering);
    fileChooser.addChoosableFileFilter(filtering);
    int selection = fileChooser.showOpenDialog( this );
    if ( selection == JFileChooser.CANCEL_OPTION )
    return false;
    if (selection == -1) {
    return false;
    File tmpfile = fileChooser.getSelectedFile();
    filename = tmpfile.toString();
    setTitle( "Smiggin Holes 2010 - " + filename );
    return true;
    static class FileChoser extends javax.swing.filechooser.FileFilter
    String extension;
    String description;
    public FileChoser(String extension, String description){
    this.extension = extension;
    this.extension = description;
    // Accept all directories and all gif, jpg, or tiff files.
    public boolean accept(File f)
    if (f != null)
    if (f.isDirectory())
    return true;
    String ext = getExtension(f); //<<<<<<<<<<<THE PROBLEM IS HERE WHEN I TRY TO GET THE EXTENSION OF THE FILE. IT CANT COMPILE
    System.out.println("aasdfasdf"+ext);
    if ((ext!=null)&&(ext.equals(extension)))
    return true;
    return false;
    // The description of this filter
    public String getDescription() {
    return "Just Text Files";
    ======================================
    Could you tell me what can I do? To get the extension of the file selected by the user?
    And What do I have to change?
    Regards,

    Hi,
    can you post your compile error and the code of getExtension().
    Regards
    Ldinka

  • Adding a window to container error

    I have this table that I want to add to a my main program.
    The table works but when I add the table module to the main program I get an error.
    Exception in thread "AWT-EventQueue-0" java.lang.IllegalArgumentException: adding a window to a container
    This is the table program
    import java.awt.*;
    import java.awt.event.*;
    import java.util.*;
    import javax.swing.*;
    import javax.swing.table.*;
    import java.io.*;
    public class TableSave extends JFrame
         private JTable table;
         public TableSave()
              String[] columnNames = { "Depth", "Density"};
              Object[][] data =
              table = new JTable(data, columnNames)
                   //  Returning the Class of each column will allow different
                   //  renderers to be used based on Class
                   public Class getColumnClass(int column)
                        return getValueAt(0, column).getClass();
              table.putClientProperty("terminateEditOnFocusLost", Boolean.TRUE);
              table.setPreferredScrollableViewportSize(table.getPreferredSize());
              JScrollPane scrollPane = new JScrollPane( table );
              getContentPane().add( scrollPane );
              //  Save table to file button.
              //  Actually the code only prints out the data,
              //  its up to you to modify the code to write it to a file
              JButton button2 = new JButton( "Save Table to File" );
              button2.addActionListener( new ActionListener()
                  JFileChooser fc=new JFileChooser(System.getProperty("user.dir"));
                        //show dialog
                   public void actionPerformed(ActionEvent e)
                        int rows = table.getRowCount();
                        int columns = table.getColumnCount();
                        //  Write out the Column Headers
                        TableColumnModel header = table.getColumnModel();
                        for (int k = 0; k < columns; k++)
                             TableColumn column = header.getColumn(k);
                             String value = (String)column.getHeaderValue();
                             //System.out.print( value );
                             //System.out.print( "|" );
                        //System.out.println();
                        //  Write out the table data
                   try{
                        int fd = fc.showSaveDialog(TableSave.this);
                       if(fd==JFileChooser.APPROVE_OPTION){
                             FileOutputStream fo=new FileOutputStream(fc.getSelectedFile());
                             PrintStream ps=new PrintStream(fo);
                        for (int j = 0; j < rows; j++)
                             for (int k = 0; k < columns; k++)
                                  Object value = table.getModel().getValueAt(j, k);
                                  ps.println(value.toString() );
                                  //System.out.print( value.toString() );
                                  //System.out.print( "|" );
                          }//System.out.println();
                     }catch(Exception ex){}
              getContentPane().add(button2, BorderLayout.SOUTH);
         public static void main(String[] args)
              TableSave frame = new TableSave();
              frame.setDefaultCloseOperation( EXIT_ON_CLOSE );
              frame.pack();
              frame.setVisible(true);
    }then I add it to the main program as follows
    public void actionPerformed (ActionEvent event)
            // Determine which object was the source of the event.
            Object source = event.getSource ();
          else if (source == menuSheet)
              count2++;
              JInternalFrame f = new JInternalFrame("mass/Density"+count2);
                f.setResizable(true);
              f.setClosable(true);
              f.setMaximizable(true);
              f.setIconifiable(true);
              f.setSize(270,420);
              f.setLocation(count2*15,count2*15);
              f.addInternalFrameListener(this);
              f.setVisible(true);
              frame.getContentPane().add(f);
                tablesave = new TableSave();
                Container pane = f.getContentPane ();
            pane.setLayout (new BorderLayout());
            pane.add (tablesave, BorderLayout.CENTER);
    Help me resolve this or offer a solution to this problem.
    regards,
    moi

    Hi there,
    Both Internal Frames and Jframe are containers.
    Jframe is a heavy weight component which you are trying to add in a lightweight internal Frame component, hence the error.
    You try having the table implementation which is just a JTable and not a Jframe (You are currently extending from JFrame), then it will work out.
    Cheers
    Ravi Sinha

  • NotSerializable error while trying to write arraylist

    I am getting a NotSerializable error while trying to write an arraylist to a file.
    Here's the part of the code causing problem
    File temp = fileOpenerAndSaver.getSelectedFile(); // fileOpenerAndSaver is a JFileChooser object which has been created and initialized and was already used to select a file with
    currentWorkingFile = new File (temp.getAbsolutePath() + ".gd");      // currentWorking file is a file object
    try
         ObjectOutput output = new ObjectOutputStream (new BufferedOutputStream(new FileOutputStream(currentWorkingFile)));
         output.writeObject(nodeList); // <-- This is the line causing problem (it is line 1475 on which exception is thrown)
         output.writeObject(edgeList);
         output.writeObject(nodesWithSelfLoop);
         output.writeObject(nextId);
         output.writeUTF(currentMessage);
         output.close();
    catch (Exception e2)
         JOptionPane.showMessageDialog (graphDrawer, "Unknown error writing.", "Error", JOptionPane.ERROR_MESSAGE);
         e2.printStackTrace();
    } As far as what nodeList is -- it's an arraylist of my own class Node which has been serialized and any object used inside the class has been serialized as well.
    Here is the declaration of nodeList:
         private ArrayList <Node> nodeList; // ArrayList to hold a list all the nodesLet me show you whats inside the node class:
    private class Node implements Serializable
         private static final long serialVersionUID = -4625153386839971250L;
         /*  edgeForThisNodeList holds all the edges that are between this node and another node
          *  nodesConnected holds all the nodes that are connected (adjacent) to this node
          *  p holds the top left corner coordinate of this node.  The centre. of this node is at (p.x + 5, p.y + 5)
          *  hasSelfLoop holds whether this node has a self loop.
          *  **NOTE**: ONLY ONE SELF LOOP IS ALLOWED FOR A NODE.
         ArrayList <Edge> edgeForThisNodeList = new ArrayList <Edge> ();
         ArrayList <Node> nodesConnected = new ArrayList <Node> ();
         Point p;
         boolean hasSelfLoop = false;
         int index = -1;
         BigInteger id;
                     ... some methods following this....
    }Here is the edge class
    private class Edge implements Serializable
         private static final long serialVersionUID = -72868914829743947L;
         Node p1, p2; // The two nodes
         Line2D line;
          * Constructor:
          * Assigns nodes provided as appropriate.
          * Also calls the addEdge method on each of the two nodes, and passes
          * "this" edge and the other node to the nodes, so that
          * this edge and the other node can be added to the
          * data of the node.
         public Edge (Node p1, Node p2)
              this.p1 = p1;
              this.p2 = p2;
              line = new Line2D.Float(p1.p.x+5,p1.p.y+5,p2.p.x+5,p2.p.y+5);
              p1.addEdge(this, p2, true);
              p2.addEdge(this, p1, false);
         }Here is the error I am getting:
    java.io.NotSerializableException: javax.swing.plaf.metal.MetalFileChooserUI
         at java.io.ObjectOutputStream.writeObject0(Unknown Source)
         at java.io.ObjectOutputStream.defaultWriteFields(Unknown Source)
         at java.io.ObjectOutputStream.writeSerialData(Unknown Source)
         at java.io.ObjectOutputStream.writeOrdinaryObject(Unknown Source)
         at java.io.ObjectOutputStream.writeObject0(Unknown Source)
         at java.io.ObjectOutputStream.writeOrdinaryObject(Unknown Source)
         at java.io.ObjectOutputStream.writeObject0(Unknown Source)
         at java.io.ObjectOutputStream.writeObject(Unknown Source)
         at MyPanel.save(MyPanel.java:1475)
         at GraphDrawer.actionPerformed(GraphDrawer.java:243)
         I inentionally did not write the whole error stack because it was way too long and I ran out of characters. But line 1475 is where I do the writeObject call. I also goet some weird not serialized exceptions before on some other classes that are not being written to the file or are not part of the object that I am writing. I serialized those classes and now it's this unknown object that's causing problems.
    Edit: The problem may be due to the JFileChooser I am using to select the file as it is a non-serializable object. But I am not trying to write it to the file and in fact am just writing the arrayLists and BigInteger as objects to the file.
    Edited by: Cricket_struck on Dec 21, 2009 1:25 PM
    Edited by: Cricket_struck on Dec 21, 2009 1:32 PM
    Edited by: Cricket_struck on Dec 21, 2009 2:16 PM

    java.io.NotSerializableException: javax.swing.plaf.metal.MetalFileChooserUIThat's a Swing component and it is clearly related to the JFileChooser.
    I also get some weird not serialized exceptions before on some other classes that are not being written to the file or are not part of the object that I am writing.That's a contradiction in terms. If you get NotSerialzableException it means the objects are being written. So they are reachable from the objects you're writing.
    Edit: The problem may be due to the JFileChooser I am using to select the file as it is a non-serializable object.JFileChooser implements Serializable, but you're right, you shouldn't try to serialize it. But clearly this is the current problem. Somewhere you have a reference to it reachable via the object(s) you are serializing.
    I suspect that Node and Edge inner classes and that you aren't aware that inner classes contain a hidden reference to their containing class. The solution for serializaition purposes is to make them static nested classes, or outer classes.

Maybe you are looking for