Is it a bug in JFileChooser?

JDK & JRE:
java version "1.4.2_02"
Java(TM) 2 Runtime Environment, Standard Edition (build 1.4.2_02-b03)
Java HotSpot(TM) Client VM (build 1.4.2_02-b03, mixed mode)
Operating System: Windows 2000 Advanced Server with sp4
Description:
Assume setting the JFileChooser's property as 'JFileChooser.FILES_AND_DIRECTORIES',
double-clicking on a directory, enter the directory but no one file is selected,
the text in the text-field that used for selected files is the name of this directory.
For example, you've selected the directoy 'D:\jdk14', enter the directory and
none is selected. Codes as below:
File f = JFileChooser.getSelectedFile();
String s = f.getAbsolutePath();
The content of the variable named 's' is 'd:\jdk14\jdk14'

Yes, it's a bug:
http://bugs.sun.com/bugdatabase/view_bug.do?bug_id=5075580

Similar Messages

  • Bug in JFileChooser (Java 1.6.0_03 running on Windows XP)?

    Hello All,
    I tried to display a JFileChooser dialog for file selection. It opens in the "My Documents" directory.
    This directory contained a big (400 megs) ZIP file.
    The JFileChooser dialog tooked a very long time to be displayed (I didn't selected this big zip file).
    If I remove the ZIP file, the JFIleChooser displays fast.
    I did the test with the JFileChooser demo from sun (http://java.sun.com/docs/books/tutorial/uiswing/components/filechooser.html), and I find the same result.
    I think that's really a bug in the implementation of JFileChooser. Can you tell me if it is possible to let sun know this problem?
    Kind regards.
    Michael Hooreman

    JFileChooser has always had a problem with Windows XP's insistence on treating Zip files as folders. That's a stupid feature anyway, and I'm surprised JFileChooser doesn't automatically bypass it. You can disable the feature by running the following command: regsvr32 /u zipfldr Note that you'll be disabling the feature in Windows, not just in Java. You can re-enable it by running the same command without the /u.

  • Anyone had problems with jFilechooser?

    I have problems with JFilechooser freezes when invoking returnVal = chooser.showDialog(this, "Select");
    For some reason it freezes the entire program, allthough sometimes (rarely), it doesn't freeze.
    Are there currently any problems with JFileChooser? I have not had any problems when embedding it in a window - only when using it on its own with JFileChooser chooser = new JFileChooser();
    Regards / Daniel

    There was a bug with JFileChooser where it would be unnecessarily slow when the directory it was showing contained huge zip files on Windows. It seems like it had something to do with the Win32 API calls they were making actually looked into all of the zip file's entries even though it didn't need to. This was fixed back in Java 6 update 10. What Java version are you using?
    If that isn't your problem, you'll have to post an SSCCE demonstrating your problem to get any help.

  • JFileChooser throws NullPointerException when in a non-traversable Dir

    Hi all
    I think I found a bug of JFileChooser. Unless one of you knows the issue and the corresponding workaround.
    It occurs when one extends JFileChooser and overrides isTraversable() to dissalow the navigation to specific
    directories. When the user then uses the JComboBox of the JFilechooser dialog to navigate to a non-allowed
    directory and from there tries to again select a not allowed directory, the following Exception gets thrown
    within the JFileChooser.showDialog method.
    To reproduce this try:
    import java.io.File;
    import javax.swing.JFileChooser;
    public class   yxJFileChooser
           extends   JFileChooser
        public boolean isTraversable(File _f)
                 if  (_f == null)       return false;
            else if (!_f.isDirectory()) return false;
            String fileToCheck = _f.getAbsolutePath().toLowerCase();
            if (fileToCheck.startsWith("c:\\windows")) return true;
            else                                       return false;
    }the try:
             yxJFileChooser fc = new yxJFileChooser();
             int ret = fc.showDialog(null,"try the combo twice. Choose both times a non traversable dir");Once you have chosen for the second time a non-valid directory (using the combo) you will get a NullPointerException:
    Is this indeed a Java VM bug or am I doing something wrong?
    My operating system is Windows XP service pack 2 and the java version I am running this with is:
    java version "1.6.0-rc"
    Java(TM) SE Runtime Environment (build 1.6.0-rc-b102)
    Java HotSpot(TM) Client VM (build 1.6.0-rc-b102, mixed mode)

    Here the Exception:
    Exception occurred during event dispatching:
    java.lang.NullPointerException
    at javax.swing.plaf.metal.MetalFileChooserUI$DirectoryComboBoxAction.actionPerformed(Unknown Source)
    at javax.swing.JComboBox.fireActionEvent(Unknown Source)
    at javax.swing.JComboBox.setSelectedItem(Unknown Source)
    at javax.swing.JComboBox.setSelectedIndex(Unknown Source)
    at javax.swing.plaf.basic.BasicComboPopup$Handler.mouseReleased(Unknown Source)
    at java.awt.AWTEventMulticaster.mouseReleased(Unknown Source)
    at java.awt.Component.processMouseEvent(Unknown Source)
    at javax.swing.JComponent.processMouseEvent(Unknown Source)
    at javax.swing.plaf.basic.BasicComboPopup$1.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.pumpEventsForFilter(Unknown Source)
    at java.awt.Dialog$1.run(Unknown Source)
    at java.awt.Dialog$3.run(Unknown Source)
    at java.security.AccessController.doPrivileged(Native Method)
    at java.awt.Dialog.show(Unknown Source)
    at javax.swing.JFileChooser.showDialog(Unknown Source)
    at yx.filearchiver.sh.getFileNameFromUser(Unknown Source)
    at yx.filearchiver.gui.pnl4ActionListener.actionPerformed(Unknown Source)
    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.plaf.basic.BasicButtonListener.mouseReleased(Unknown Source)
    at java.awt.AWTEventMulticaster.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)

  • 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 ------*/

  • Resizng JFileChooser problem!!

    Hi,
    i have really wierd problem with JFileChooser.FileChooser is displayed very wide.It fills my screen.I use j2sdk1.4 and Windows XP.I used
    fileChooser.setPreferredSize(new Dimension(450,280));
    it is resized.But now ComboBox that allows me to choose where to save file is shown too long.Also buttons for "up one level","list","details" are not displayed.Please help me.
    greetings

    This is because there is a long string in the drop-down list at the top (possibly you have a meapped drive with a long path). For some reason (a bug?) JFileChooser seems to resize the dor-down list (and hence itself) to fit the longest path - at least on XP

  • JFileChooser has a bug in 1.6?

    Hi,
    With JRE 1.5/1.4, I believed when you bring up the JFileChooser dialog and select the "Detail" view, you will get 4 columns: Name, Size, Type, and Modified.
    With 1.5/1.4, there seems to be 2 problems:
    1. You cannot sort the list by clicking on the column header
    2. The timestamp doesn't reflect the timezone.
    With 1.6, you get only 3 columns: Name, Size, Modified. However, the values in the Modified column should by "Type" instead. Is this a bug with the JFileChooser in 1.6? Have others seen the same thing?
    --Chung                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                   

    In java 1.6.0_06 it works fine...

  • JFileChooser SetSelectedFile() bug

    Hi,
    I am having problems using a JFileChooser to save a file in JDK1.3.
    The problem is that selecting a directory overwrites the filename in the file chooser, i.e. if a user types in a filename, then decides to change directories, their filename will be overwritten with the name of the directory they just navigated to.
    This is a known bug, but I have been unable to find a solution where both:
    a) the filename is NOT overwritten.
    b) selecting the "save" button when a directory is selected OPENS the directory.
    The solutions I have found so far solve a), but cause b) to stop working.
    This has been resolved in 1.4.1 I think, but I need it to work with 1.3.
    Has anyone got a solution, preferably one that isn't tied in to a particular look and feel?
    Cheers.

    Have you tried
       yourFileChooser.setFileSelectionMode(JFilesChooser.FILES_ONLY); ?

  • JFileChooser bug?

    Hi,
    I've encountered a strange thing (is it a bug?) in JFileChooser. It goes like this:
    in the Open File chooser, when I click on the name of a file, it goes to edit mode of that filename. If I click outside so as to cancel the renaming, a file in the directory gets deleted but its filename appears in the Open textfield!!!
    I am wondering whether it has something to do with my code, or something to do with the JFileChooser itself.
    My code looks like this:
    public void actionPerformed(ActionEvent e) {
    try{
    if (fc == null)
    fc = new JFileChooser();
    else
    fc.setVisible(true);
    fc.setCurrentDirectory(new File("robotSim/programs"));
    int returnedVal = fc.showOpenDialog(dialog);
    if (returnedVal == JFileChooser.APPROVE_OPTION){
    File file = fc.getSelectedFile();
    dialog.setFile(file);
    MyIO fileIO = new MyIO(file);
    String[] lines = fileIO.toArray();
    if (lines.length != 0){
    for (int i = 0; i < lines.length; i++)
    System.out.println(lines);
    programPanel = Converter.TextToBasicProgramPanel(lines);
    else {
    programPanel = new BasicProgramPanel();
    JOptionPane optionPane = new JOptionPane();
    optionPane.showMessageDialog(dialog, "Empty program!", "Warning",
    JOptionPane.WARNING_MESSAGE);
    dialog.setProgramPanel(programPanel);
    // done!
    System.out.println("OpenFileButtonListener: program panel from " +
    file.getName() + " loaded");
    catch(Exception ex){
    System.out.println("OpenFileButtonListener: " + ex);
    Is there a listener that takes care of the events performed in the file explorer window? If so, can I disable it?
    any comment is welcomed! Thx in advance.

    This is absolutely a bug. And it is a serious one at that.
    I found out about it while working on a project under Solaris 8.
    I just filed a bug report to Sun!

  • JFileChooser crashes JVM - bug basically ignored. What can I do?

    See:
    http://bugs.sun.com/bugdatabase/view_bug.do?bug_id=7160713
    The bug has been marked as incomplete,needs more info, and "Low Prioroty" - Yet there is no mechanism to provide any more information. There is no way to add comments, or vote. The bug brings down the entire JVM with a native crash and it is trivial to reproduce.
    I would provide any information that is asked of me - but I need a way to do it. I think I got an email request for info (It's been a while now), but replies to the email bounced, and as noted above the bug page has no way to give feedback.
    Use any JFileChooser, click on the "Details" view. Then start clicking on column headings... after a few clicks the JVM crashes. Tested again with 7u6 - still crashes.

    This reproduces the problem more reliably for me.
    * JFileChooser Windows Crash
    package filechoosercrash;
    import java.awt.AWTEvent;
    import java.awt.BorderLayout;
    import java.awt.Robot;
    import java.awt.Toolkit;
    import java.awt.Window;
    import java.awt.event.AWTEventListener;
    import java.awt.event.ActionEvent;
    import java.awt.event.ActionListener;
    import java.awt.event.InputEvent;
    import java.util.concurrent.CountDownLatch;
    import java.util.logging.Level;
    import java.util.logging.Logger;
    import javax.swing.JButton;
    import javax.swing.JDialog;
    import javax.swing.JFileChooser;
    import javax.swing.JFrame;
    import javax.swing.JLabel;
    import javax.swing.LookAndFeel;
    import javax.swing.SwingUtilities;
    import javax.swing.UIManager;
    import javax.swing.UIManager.LookAndFeelInfo;
    import javax.swing.UnsupportedLookAndFeelException;
    * @author scott
    public class FileChooserCrash {
         static CountDownLatch latch = new CountDownLatch(1);
         static JFrame frame;
         static JButton button;
         static JFileChooser chooser;
         static Robot robot;
         private static AWTEventListener terminator = new AWTEventListener() {
              @Override
              public void eventDispatched(AWTEvent event) {
                   System.exit(10);
          * @param args the command line arguments
         public static void main(final String[] args) throws Exception {
              SwingUtilities.invokeLater(new Runnable() {
                   @Override
                   public void run() {
                        try {
                             swingMain(args);
                        } catch (Exception ex) {
                             Logger.getLogger(FileChooserCrash.class.getName()).log(Level.SEVERE, null, ex);
              latch.await();
              // do the clicks
              sleep(3000);
              Toolkit.getDefaultToolkit().addAWTEventListener(terminator, AWTEvent.KEY_EVENT_MASK);
              long now = System.currentTimeMillis();
              for (int c = 0; c < 10; c++) {
                   Window w = JDialog.getWindows()[1]; // better be there!
                   System.out.println("w=" + w);
                   int detailsX = w.getX() + w.getWidth() - 36;
                   int detailY = w.getY() + 50;
                   int headingY = w.getY() + 100;
                   System.out.println("details at " + detailsX + ", " + detailY);
                   // Click details
                   robot.mouseMove(detailsX, detailY);
                   clickMouse();
                   sleep(100);
                   // Click column headings
                   while (System.currentTimeMillis() - now < 2 * 1000) {
                        int headingX = w.getX() + (w.getWidth()/2) + (int) (Math.random() * (w.getWidth()/2));
                        robot.mouseMove(headingX, headingY);
                        clickMouse();
                        sleep(300);
                   // Cancel
                   robot.mouseMove(w.getX() + w.getWidth() - 36, w.getY() + w.getHeight() - 36);
                   clickMouse();
                   sleep(300);
                   // re-open
                   robot.mouseMove(frame.getX() + 36, frame.getY() + 36);
                   clickMouse();
                   sleep(1000);
                   now = System.currentTimeMillis();
         private static void sleep(int millis) {
              try {
                   Thread.sleep(millis);
              } catch (InterruptedException ex) {
         private static void clickMouse() {
              robot.mousePress(InputEvent.BUTTON1_DOWN_MASK);
              sleep(100);
              robot.mouseRelease(InputEvent.BUTTON1_DOWN_MASK);
         private static void swingMain(String[] args) throws Exception {
              //switchToNimbus();
              robot = new Robot();
              frame = new JFrame("JFileChooser Crash Test");
              button = new JButton("Start...");
              button.addActionListener(new ActionListener() {
                   @Override
                   public void actionPerformed(ActionEvent e) {
                        showFileChooser(frame);
              frame.getContentPane().add(button, BorderLayout.CENTER);
              frame.getContentPane().add(new JLabel("Press \"Start...\" and let go of the mouse.  Robot will be used to change FileChooser to details view and then quickly click column headings until the crash."), BorderLayout.SOUTH);
              frame.pack();
              frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
              frame.setVisible(true);
         static void showFileChooser(JFrame parent) {
              chooser = new JFileChooser("C:\\");
              latch.countDown();
              chooser.showOpenDialog(parent);
         private static void switchToNimbus() throws UnsupportedLookAndFeelException, IllegalAccessException, InstantiationException, ClassNotFoundException {
              for (LookAndFeelInfo laf : UIManager.getInstalledLookAndFeels()) {
                   if (laf.getName().startsWith("Nimbus")) {
                        System.out.println("Using " + laf.getName());
                        UIManager.setLookAndFeel(laf.getClassName());
                        break;
    }

  • JFileChooser problem - A bug ???

    Hi all,
    i am facing a unique problem with the JFileChooser. when i go to the "Look in" drop down list and select "Network Neighborhood", what i expect is to get a list of all computers on my LAN. i do get it, but the filechooser does seem to recognise the system names. the names that r displayed seem to be kind of substrings of "Network".
    E.g: etwork, ft Network, soft Network etc..., instead of proper system names.
    but when i double click on a folder, then it displays the shared folder names correctly, and also identifies the system name. it says something like:
    "folderName" on "systemName"
    if the filechooser is able to recognise the system name here, then why does it not display the system names properly in the aforesaid place (ie, when i select Network Neighborhood) initially.
    am running jdk ver 1.4, on a windows 98 system. is it somekind of a bug or am i missing something that i need to do ? could not find any help from the API.
    any idea anyone ???
    thanks
    - satyen

    1.4.2 has a fix for JFileChooser, although I am not
    sure its this problem, or hopefully the one I see
    often, when I click the drop down box to navigate to a
    network drive, it sometimes takes a VERY long time, on
    the order of hours, for the drop down to show up. On
    of our clients is seeing this now, so I am not sure
    why this is.The problem here is that Windows98 Network communication is appalling slow a lot of the time and some bits of it is broken.
    Getting the members list from a network can take an age simply because you sometimes have to broadcast a query on that network to find all the machines on it. This is not a Java related problem (although I suspect that VM support for Windows98 has slipped in priority ).

  • JFileChooser home button shows desktop - bug?

    Running jdk 1.4.1 on XP I would expect the home button to direct the user to his or her "My Documents" folder. However, when clicking the home button, the desktop is shown. Is this a known bug? Is there a workaround?
    Randahl

    i think you can decide which directory is the home directory.
    JFileChooser
    public JFileChooser()Constructs a JFileChooser pointing to the user's default directory. This default depends on the operating system. It is typically the "My Documents" folder on Windows, and the user's home directory on Unix.
    This is taken from the JFileChooser interface... its not a bug its the default value. You can alterate that using a different constructor such as
    public JFileChooser(String currentDirectoryPath)Constructs a
    JFileChooser using the given path. Passing in a null string causes the file chooser to point to the user's default directory. This default depends on the operating system. It is typically the "My Documents" folder on Windows, and the user's home directory on Unix.
    Hope this helps

  • Bug JFileChooser freeze!

    I can't use JFileChooser. When I write in my aplication: new JFileChooser(); the aplication freeze (examples with JFileChooser from sun have the same problem).
    I have windows Xp and jdk 1.6.0_03(same in jdk 1.6.0_04), my friends that use the WindowsXp and Jdk 1.6 don't have this problem.
    Could someone advice what to do to get rid of this bug?
    Thank you.

    I solved the problem.
    I had a bad sortcut(con.lnk) in desktop, I couldn't delete this file(windows or dos). Finally I used Unlocker 1.8 that help me to delete this bad link (con.lnk) and now evrything works fine :)
    The problem wasn't in my aplication, I write a simple HelloWord.java and include new JFileChooser() and aplication freeze. As I said I had the same problem running examples with JFileChooser from http://java.sun.com/docs/books/tutorial/uiswing/components/filechooser.html .

  • Help, experiencing minor bugs in program

    this is supposed to use rectangles and you should be able to load and save and they have colors and do a few more things with them, the loading is where it doesn't work.
    *-------------------------------------------------------------- 80 columns ---|
    * This is the main class for the application. It is built along the same
    * lines as the Editor class of project 1. It has a constructor, two instance
    * methods, and a static main()  that kicks the whole thing off.
    * The two instance methods are a menu creation method, and a menuItems
    * initialisation method.  The constructor instantiates the window
    * and sets up its internals by creating and installing the drawing canvas,
    * toolbar, and menus. All of the code works correctly as is and should
    * require no changes.
    * @version      1.1 15/04/01
    * @author       Julie Zelenski
    * @author       Restructured by Ian A. Mason
    * @see       javax.swing.JFrame
    * @see       javax.swing.JMenuBar
    * @see       javax.swing.JMenuItem
    * @see       javax.swing.JMenu
    import java.awt.*;
    import javax.swing.*;
    import java.awt.event.*;
    public class JavaDraw extends JFrame {
        final Toolbar toolbar = new Toolbar();
        final DrawingCanvas canvas = new DrawingCanvas(toolbar, 350, 350);
        final int menuMask = Toolkit.getDefaultToolkit().getMenuShortcutKeyMask();
        final JMenuBar mb = new JMenuBar();
        final String[]
             fileMenuItems = {"Clear all", "Load file", "Save to file", "Quit"};
        final int[] fileKeyCodes = {KeyEvent.VK_N, KeyEvent.VK_O, KeyEvent.VK_S, KeyEvent.VK_Q};
        final ActionListener[] fileActionListeners = {
         new ActionListener() {
              public void actionPerformed(ActionEvent e) {
                  canvas.clearAll();}},
         new ActionListener() {
              public void actionPerformed(ActionEvent e) {
                  canvas.loadFile();}},
         new ActionListener() {
              public void actionPerformed(ActionEvent e) {
                  canvas.saveToFile();}},
         new ActionListener() {
              public void actionPerformed(ActionEvent e) {
                  System.exit(0);}}
        final String[] editMenuItems = {"Cut", "Copy", "Paste", "Delete"};
        final int[] editKeyCodes = {KeyEvent.VK_X, KeyEvent.VK_C, KeyEvent.VK_V, KeyEvent.VK_BACK_SPACE};
        final int[] editMenuMasks = {menuMask, menuMask, menuMask, 0};
        final ActionListener[] editActionListeners = {
         new ActionListener() {
              public void actionPerformed(ActionEvent e) { canvas.cut();}},
         new ActionListener() {
              public void actionPerformed(ActionEvent e) { canvas.copy();}},
         new ActionListener() {
              public void actionPerformed(ActionEvent e) { canvas.paste();}},
         new ActionListener() {
              public void actionPerformed(ActionEvent e) { canvas.delete();}}
        final String[] layeringMenuItems = {"Bring to front", "Send to back"};
        final int[]    layeringKeyCodes = {KeyEvent.VK_F, KeyEvent.VK_B};
        final ActionListener[] layeringActionListeners = {
         new ActionListener() {
              public void actionPerformed(ActionEvent e) {
                  canvas.bringToFront();}},
         new ActionListener() {
              public void actionPerformed(ActionEvent e) {
                  canvas.sendToBack();}}
        private JavaDraw(){
         super("JavaDraw!");
         toolbar.setCanvas(canvas);
         getContentPane().add(toolbar, BorderLayout.SOUTH);
         getContentPane().add(canvas, BorderLayout.CENTER);
         createMenus();
         setJMenuBar(mb);
         setLocation(100, 20);
         pack();
         setVisible(true);
        static public void main(String[] args){
         JavaDraw javaDraw = new JavaDraw();
        private void initMenus(JMenu m,
                      String  miLabel,
                      int keyCode,
                      int menuMask,
                      ActionListener al){
         JMenuItem mi = new JMenuItem(miLabel);
         m.add(mi);
         mi.addActionListener(al);
         mi.setAccelerator(KeyStroke.getKeyStroke(keyCode, menuMask));
        private void createMenus(){
         JMenu m;
         m = new JMenu("File");
         for(int i = 0; i < fileMenuItems.length; i++)
             initMenus(m,
                    fileMenuItems,
              fileKeyCodes[i],
              menuMask,
              fileActionListeners[i]);
         mb.add(m);
         m = new JMenu("Edit");
         for(int i = 0; i < editMenuItems.length; i++)
         initMenus(m,
              editMenuItems[i],
              editKeyCodes[i],
              editMenuMasks[i],
              editActionListeners[i]);
         mb.add(m);
         m = new JMenu("Layering");
         for(int i = 0; i < layeringMenuItems.length; i++)
         initMenus(m,
              layeringMenuItems[i],
              layeringKeyCodes[i],
              menuMask,
              layeringActionListeners[i]);
         mb.add(m);
    *-------------------------------------------------------------- 80 columns ---|
    * The DrawingCanvas class a small extension of JComponent
    * @version 1.1 15/04/01
    * @author Julie Zelenski
    * @author (touched up by Ian A. Mason)
    * @see javax.swing.JComponent
    import java.awt.*;
    import java.awt.event.*;
    import javax.swing.*;
    import javax.swing.event.*;
    import java.util.*;
    public class DrawingCanvas extends JComponent{
    static final int DRAG_NONE = 0;
    static final int DRAG_CREATE = 1;
    static final int DRAG_RESIZE = 2;
    static final int DRAG_MOVE = 3;
    // list of all shapes on canvas
    protected Vector allShapes;          
    // currently selected shape (can be null at times)
    protected Rect selectedShape;
    // reference to toolbar to message for tool&color settings
    protected Toolbar toolbar;
    protected Rect clipboard=null;          
    /* These are the unimplemented menu commands. The menus are already
    * set up to send the correct messages to the canvas, but the
    * method bodies themselves are currently completely empty. It will
    * be your job to fill them in!
    public void cut() {
         copy();
         delete();
    public void copy() {
         int x=(int)selectedShape.getBounds().getX();
         int y=(int)selectedShape.getBounds().getY();
         Point p=new Point(x,y);
         clipboard=new Rect(p,this);
         clipboard.setBounds(selectedShape.getBounds());
    public void paste() {
         if(clipboard==null)
              return;
         allShapes.add(clipboard);
         setSelectedShape(clipboard);
         copy();
         this.repaint();
    public void delete() {
         if(selectedShape==null)
              return;
         else{
         int num=allShapes.indexOf(selectedShape);
         allShapes.remove(num);
         selectedShape=null;
         this.repaint();
    public void clearAll() {
         allShapes.removeAllElements();
         this.repaint();
    public void loadFile() {
         Load load=new Load(this);
         load.setSize(250,200);
         load.validate();
         load.setVisible(true);
    public void done(Vector vect){
         allShapes.removeAllElements();
         for(int i=0;i<vect.size();i++){
              allShapes.add(vect.elementAt(i));
         this.repaint();
    public void saveToFile() {
         Save save=new Save(allShapes);
         save.setSize(250,200);
         save.validate();
         save.setVisible(true);
    public void bringToFront() {
         if(selectedShape==null)
              return;
         int size=allShapes.size();
         int index=allShapes.indexOf(selectedShape);
         for(int i=index+1;i<=size-1;i++){
              allShapes.set(i-1,allShapes.elementAt(i));
         allShapes.set(size-1,selectedShape);
         this.repaint();
    public void sendToBack() {
         if(selectedShape==null)
              return;
         int index=allShapes.indexOf(selectedShape);
         for(int i=index-1;i>=0;i--){
              allShapes.remove(allShapes.elementAt(i+1));
              allShapes.add(i+1,allShapes.elementAt(i));
         allShapes.remove(allShapes.elementAt(0));
         allShapes.add(0,selectedShape);
         this.repaint();
    * Constructor for creating a new empty DrawingCanvas. We set up
    * our size and background colors, instantiate an empty vector of shapes,
    * and install a listener for mouse events using our inner class
    * CanvasMouseHandler
    public DrawingCanvas(Toolbar tb, int width, int height){
         setPreferredSize(new Dimension(width, height));
         setBackground(Color.white);
         toolbar = tb;
         allShapes = new Vector();
         selectedShape = null;
         CanvasMouseHandler handler = new CanvasMouseHandler();
         addMouseListener(handler);
         addMouseMotionListener(handler);
    * All components are responsible for drawing themselves in
    * response to repaint() requests. The standard method a component
    * overrides is paint(Graphics g), but for Swing components, the default
    * paint() handler calls paintBorder(), paintComponent() and paintChildren()
    * For a Swing component, you override paintComponent and do your
    * drawing in that method. For the drawing canvas, we want to
    * clear the background, then iterate through our shapes asking each
    * to draw. The Graphics object is clipped to the region to update
    * and we use to that avoid needlessly redrawing shapes outside the
    * update region.
    public void paintComponent(Graphics g){
         Rectangle regionToRedraw = g.getClipBounds();
         g.setColor(getBackground());
         g.fillRect(regionToRedraw.x, regionToRedraw.y,
              regionToRedraw.width, regionToRedraw.height);
         Iterator iter = allShapes.iterator();
         while (iter.hasNext())
         ((Rect)iter.next()).draw(g, regionToRedraw);
    * Changes the currently selected shape. There is at most
    * one shape selected at a time on the canvas. It is possible
    * for the selected shape to be null. Messages the shape to
    * change its selected state which will in turn refresh the
    * shape with the knobs active.
    protected void setSelectedShape(Rect shapeToSelect) {
         // if change in selection
         if (selectedShape != shapeToSelect) {
         // deselect previous selection
         if (selectedShape != null)
              selectedShape.setSelected(false);
         // set selection to new shape
         selectedShape = shapeToSelect;
         if (selectedShape != null) {
              shapeToSelect.setSelected(true);
    * A hit-test routine which finds the topmost shape underneath a
    * given point.We search Vector of shapes in back-to-front order
    * since shapes created later are added to end and drawn last, thus
    * appearing to be "on top" of the earlier ones. When a click comes
    * in, we want to select the top-most shape.
    protected Rect shapeContainingPoint(Point pt){
         for (int i = allShapes.size()-1; i >= 0; i--) {
         Rect r = (Rect)allShapes.elementAt(i);
         if (r.inside(pt)) return r;
         return null;
    * The inner class CanvasMouseHandler is the object that handles the
    * mouse actions (press, drag, release) over the canvas. Since there is
    * a bit of state to drag during the various operations (which shape,
    * where we started from, etc.) it is convenient to encapsulate all that
    * state with this little convenience object and register it as the
    * handler for mouse events on the canvas.
    protected class CanvasMouseHandler
         extends MouseAdapter implements MouseMotionListener {
         Point dragAnchor;          
         // variables using to track state during drag operations
         int dragStatus;
         /** When the mouse is pressed we need to figure out what
         * action to take. If the tool mode is arrow, the click might
         * be a select, move or reisze. If the tool mode is one of the
         * shapes, the click initiates creation of a new shape.
         public void mousePressed(MouseEvent event){
         Rect clicked = null;
         Point curPt = event.getPoint();
         // first, determine if click was on resize knob of selected shape
         if (toolbar.getCurrentTool() == Toolbar.SELECT) {
              if (selectedShape != null &&
              (dragAnchor = selectedShape.getAnchorForResize(curPt))
              != null) {
              // drag will resize this shape
              dragStatus = DRAG_RESIZE;     
              } else if ((clicked = shapeContainingPoint(curPt)) != null) {
              // if not, check if any shape was clicked
              setSelectedShape(clicked);
              // drag will move this shape      
              dragStatus = DRAG_MOVE;
              dragAnchor = curPt;
              } else {     
              // else this was a click in empty area,
              // deselect selected shape,
              setSelectedShape(null);
              // drag does nothing in this case
              dragStatus = DRAG_NONE;
         } else {
              Rect newShape = new Rect(curPt, DrawingCanvas.this);
              // create rect here
              allShapes.add(newShape);
              setSelectedShape(newShape);
              dragStatus = DRAG_CREATE;          
              // drag will create (resize) this shape
              dragAnchor = curPt;
         /** As the mouse is dragged, our listener will receive periodic
         * updates as mouseDragged events. When we get an update position,
         * we update the move/resize event that is in progress.
         public void mouseDragged(MouseEvent event){
         Point curPt = event.getPoint();
         switch (dragStatus) {
         case DRAG_MOVE:
              selectedShape.translate(curPt.x - dragAnchor.x,
                             curPt.y - dragAnchor.y);
              // update for next dragged event
              dragAnchor = curPt;
              break;
         case DRAG_CREATE: case DRAG_RESIZE:
              selectedShape.resize(dragAnchor, curPt);
              break;
         public void mouseMoved(MouseEvent e) {}
    /** A little helper routine that will be useful for the load & save
    * operations. It brings up the standard JFileChooser dialog and
    * allows the user to specify a file to open or save. The return
    * value is the full path to the chosen file or null if no file was
    * selected.
    protected String filenameChosenByUser(boolean forOpen){
         JFileChooser fc = new JFileChooser(System.getProperty("user.dir") +
                             java.io.File.separator + "Documents");
         int result = (forOpen? (fc.showOpenDialog(this)) :
              fc.showSaveDialog(this));
         java.io.File chosenFile = fc.getSelectedFile();
         if (result == JFileChooser.APPROVE_OPTION && chosenFile != null)
         return chosenFile.getPath();
         return null;
         // return null if no file chosen or dialog cancelled
    import javax.swing.*;
    import java.awt.*;
    import java.awt.event.*;
    import java.util.Vector;
    import java.io.*;
    class Load extends JFrame implements ActionListener, Serializable{
         Container contentPane;
         JTextField jtf;
         JButton jb;
         Object obj=null;
         Load load;
         Thread thread;
         DrawingCanvas draw;
         public Load(DrawingCanvas dc){
              draw=dc;
              contentPane=getContentPane();
              contentPane.setLayout(new FlowLayout());
              jtf=new JTextField(20);
              jb=new JButton("Load");
              jb.addActionListener(this);
              contentPane.add(jtf);
              contentPane.add(jb);
         public void actionPerformed(ActionEvent e){
              String text=jtf.getText();
              SimpleObjectReader reader=SimpleObjectReader.openFileForReading(text+".shp");
              if(reader==null){
                   System.out.println("Couldn't open file!");
                   return;
              obj=reader.readObject();
              reader.close();
              draw.done((Vector)obj);
              this.setVisible(false);
    import javax.swing.*;
    import java.awt.event.*;
    import java.awt.*;
    import java.util.Vector;
    import java.io.*;
    class Save extends JFrame implements ActionListener, Serializable{
         Container contentPane;
         JTextField jtf;
         Vector shapes;
         JButton jb;
         public Save(Vector shapeVector){
              shapes=shapeVector;
              contentPane=getContentPane();
              contentPane.setLayout(new FlowLayout());
              jtf=new JTextField(20);
              jb=new JButton("Save");
              jb.addActionListener(this);
              contentPane.add(jtf);
              contentPane.add(jb);
         public void actionPerformed(ActionEvent e){
              String text=jtf.getText();
              SimpleObjectWriter writer=SimpleObjectWriter.openFileForWriting(text+".shp");
              if(writer==null){
                   System.out.println("Couldn't open file!");
                   return;
              writer.writeObject(shapes);
              writer.close();
              this.setVisible(false);
    *-------------------------------------------------------------- 80 columns ---|
    * The RectShape class defines a simple rectangular shape object.
    * It tracks its bounding box, selected state, and the canvas it is being
    * drawn in. It has some basic methods to select, move, and resize the
    * rectangle. It has methods that draw the shape in the selected or unselected
    * states and updates the canvas whenever the state or bounds of the rectangle
    * change. The code that is there works properly, but you will need to extend
    * and change the code to support additional features.
    * @version 1.1 15/04/01
    * @author Julie Zelenski
    * @author (touched up by Ian A. Mason)
    import java.awt.*;
    import java.io.*;
    public class Rect implements Serializable{     
    protected Rectangle bounds;
    protected boolean isSelected;
    public Color color;
    public DrawingCanvas canvas;
    protected static final int KNOB_SIZE = 6;
    protected static final int NONE = -1;
    protected static final int NW = 0;
    protected static final int SW = 1;
    protected static final int SE = 2;
    protected static final int NE = 3;
    /** The constructor that creates a new zero width and height rectangle
    * at the given position in the canvas.
    public Rect(Point start, DrawingCanvas dcanvas){
         canvas = dcanvas;
         bounds = new Rectangle(start);
         color=canvas.toolbar.getCurrentColor();
    /** The "primitive" for all resizing/moving/creating operations that
    * affect the rect bounding box. The current implementation just resets
    * the bounds variable and triggers a re-draw of the union of the old &
    * new rectangles. This will redraw the shape in new size and place and
    * also "erase" if bounds are now smaller than before. It is a good
    * design to have all changes to a critical variable bottleneck through
    * one method so that you can be sure that all the updating that goes
    * with it only needs to be implemented in this one place. If any of your
    * subclasses have additional work to do when the bounds change, this is
    * the method to override. Make sure that any methods that change the
    * bounds call this method instead of directly manipulating the variable.
    protected void setBounds(Rectangle newBounds){
         Rectangle oldBounds = bounds;
         bounds = newBounds;
         updateCanvas(oldBounds.union(bounds));
    /** The resize operation is called when first creating a rect, as well as
    * when later resizing by dragging one of its knobs. The two parameters
    * are the points that define the new bounding box. The anchor point
    * is the location of the mouse-down event during a creation operation
    * or the opposite corner of the knob being dragged during a resize
    * operation. The end is the current location of the mouse. If you
    * create the smallest rectangle which encloses these two points, you
    * will have the new bounding box. Use the setBounds() primitive which
    * is the bottleneck we are using for all geometry changes, it handles
    * updating and redrawing.
    public void resize(Point anchor, Point end){
         Rectangle newRect = new Rectangle(anchor);
         // creates smallest rectange which
         // includes both anchor & end
         newRect.add(end);
         // reset bounds & redraw affected areas
         setBounds(newRect);      
    public Rectangle getBounds(){
         return bounds;
    /** The translate operation is called when moving a shape by dragging in
    * the canvas. The two parameters are the delta-x and delta-y to move
    * by. Note that either or both can be negative. Create a new rectangle
    * from our bounds and translate and then go through the setBounds()
    * primitive to change it.
    public void translate(int dx, int dy){
         Rectangle newRect = new Rectangle(bounds);
         newRect.translate(dx, dy);
         setBounds(newRect);
    /** Used to change the selected state of the shape which will require
    * updating the affected area of the canvas to add/remove knobs.
    public void setSelected(boolean newState){
         isSelected = newState;
         // need to erase/add knobs
         // including extent of extended bounds
         updateCanvas(bounds, true);
    /** The updateCanvas() methods are used when the state has changed
    * in such a way that it needs to be refreshed in the canvas to properly
    * reflect the new settings. The shape should take responsibility for
    * messaging the canvas to properly update itself. The appropriate AWT/JFC
    * way to re-draw a component is to send it the repaint() method with the
    * rectangle that needs refreshing. This will cause an update() event to
    * be sent to the component which in turn will call paint(), where the
    * real drawing implementation goes. See the paint() method in
    * DrawingCanvas to see how it is implemented.
    protected void updateCanvas(Rectangle areaOfChange, boolean enlargeForKnobs){
         Rectangle toRedraw = new Rectangle(areaOfChange);
         if (enlargeForKnobs)
         toRedraw.grow(KNOB_SIZE/2, KNOB_SIZE/2);
         canvas.repaint(toRedraw);
    protected void updateCanvas(Rectangle areaOfChange){
         updateCanvas(areaOfChange, isSelected);
    /** When the DrawingCanvas needs a shape to draw itself, it sends a draw
    * message, passing the graphics context and the current region being
    * redrawn. If the shape intersects with that region, it must draw itself
    * doing whatever it takes to properly represent itself in the canvas
    * (colors, location, size, knobs, etc.) by messaging the Graphics object.
    public void draw(Graphics g, Rectangle regionToDraw){
         if (!bounds.intersects(regionToDraw))
         return;
         g.setColor(color);
         g.fillRect(bounds.x, bounds.y, bounds.width, bounds.height);
         if (isSelected) { // if selected, draw the resizing knobs
         // along the 4 corners
         Rectangle[] knobs = getKnobRects();
         for (int i = 0; i < knobs.length; i++)
              g.fillRect(knobs[i].x, knobs[i].y,
                   knobs[i].width, knobs[i].height);
    /** When the DrawingCanvas needs to determine which shape is under
    * the mouse, it asks the shape to determine if a point is "inside".
    * This method should returns true if the given point is inside the
    * region for this shape. For a rectangle, any point within the
    * bounding box is inside the shape.
    public boolean inside(Point pt){
         return bounds.contains(pt);
    /** When needed, we create the array of knob rectangles on demand. This
    * does mean we create and discard the array and rectangles repeatedly.
    * These are small objects, so perhaps it is not a big deal, but
    * a valid alternative would be to store the array of knobs as an
    * instance variable of the Shape and and update the knobs as the bounds
    * change. This means a little more memory overhead for each Shape
    * (since it is always storing the knobs, even when not being used) and
    * having that redundant data opens up the possibility of bugs from
    * getting out of synch (bounds move but knobs didn't, etc.) but you may
    * find that a more appealing way to go. Either way is fine with us.
    * Note this method provides a nice unified place for one override from
    * a shape subclass to substitute fewer or different knobs.
    protected Rectangle[] getKnobRects(){
         Rectangle[] knobs = new Rectangle[4];
         knobs[NW] = new Rectangle(bounds.x - KNOB_SIZE/2,
                        bounds.y - KNOB_SIZE/2, KNOB_SIZE, KNOB_SIZE);
         knobs[SW] = new Rectangle(bounds.x - KNOB_SIZE/2,
                        bounds.y + bounds.height - KNOB_SIZE/2,
                        KNOB_SIZE, KNOB_SIZE);
         knobs[SE] = new Rectangle(bounds.x + bounds.width - KNOB_SIZE/2,
                        bounds.y + bounds.height - KNOB_SIZE/2,
                        KNOB_SIZE, KNOB_SIZE);
         knobs[NE] = new Rectangle(bounds.x + bounds.width - KNOB_SIZE/2,
                        bounds.y - KNOB_SIZE/2,
                        KNOB_SIZE, KNOB_SIZE);
         return knobs;
    /** Helper method to determine if a point is within one of the resize
    * corner knobs. If not selected, we have no resize knobs, so it can't
    * have been a click on one. Otherwise, we calculate the knob rects and
    * then check whether the point falls in one of them. The return value
    * is one of NW, NE, SW, SE constants depending on which knob is found,
    * or NONE if the click doesn't fall within any knob.
    protected int getKnobContainingPoint(Point pt){
         // if we aren't selected, the knobs
         // aren't showing and thus there are no knobs to check
         if (!isSelected) return NONE;
         Rectangle[] knobs = getKnobRects();
         for (int i = 0; i < knobs.length; i++)
         if (knobs[i].contains(pt))
              return i;
         return NONE;
    /** Method used by DrawingCanvas to determine if a mouse click is starting
    * a resize event. In order for it to be a resize, the click must have
    * been within one of the knob rects (checked by the helper method
    * getKnobContainingPoint) and if so, we return the "anchor" ie the knob
    * opposite this corner that will remain fixed as the user drags the
    * resizing knob of the other corner around. During the drag actions of a
    * resize, that fixed anchor point and the current mouse point will be
    * passed to the resize method, which will reset the bounds in response
    * to the movement. If the mouseLocation wasn't a click in a knob and
    * thus not the beginning of a resize event, null is returned.
    public Point getAnchorForResize(Point mouseLocation){
         int whichKnob = getKnobContainingPoint(mouseLocation);
         // no resize knob is at this location
         if (whichKnob == NONE)
         return null;
         switch (whichKnob) {
         case NW: return new Point(bounds.x + bounds.width,
                        bounds.y + bounds.height);
         case NE: return new Point(bounds.x, bounds.y + bounds.height);
         case SW: return new Point(bounds.x + bounds.width, bounds.y);
         case SE: return new Point(bounds.x, bounds.y);
         return null;
    import java.io.*;
    * SimpleObjectReader is a small class to wrap around the usual ObjectStream
    * to shield you from the exception handling which we haven't yet gotten
    * to in class.
    * <P>It has just three methods of note: one to open a new file for reading,
    * one to read an object from an open file, and one to close the file when done.
    * <P>Any object that you attempt to read must properly implement the Serializable
    * interface. Here is a simple example that shows using the SimpleFileReader to
    * to rehydrate objects from a file and print them:
    * <PRE>
    * SimpleObjectReader reader = SimpleObjectReader.openFileForReading("shapes");
    * if (reader == null) {
    * System.out.println("Couldn't open file!");
    * return;
    * Object obj;
    * while ((obj = reader.readObject()) != null)
    * System.out.println(obj);
    * reader.close();
    * </PRE>
    * <P>You are free to edit or extend this class, but we don't expect that
    * you should need to make any changes.
    * @version 1.1 15/04/01
    * @author Julie Zelenski
    * @author (touched up by Ian A. Mason)
    public class SimpleObjectReader {
    private ObjectInputStream ois;
    * Opens a new file for reading. The filename can either be a relative
    * path, which will be relative to the working directory of the program
    * when started, or an absolute path. If the file exists and can be
    * opened, a new SimpleObjectReader is returned. If the file cannot be
    * opened (for any reason: wrong name, wrong path, lack of permissions, etc.)
    * null is returned.
    public static SimpleObjectReader openFileForReading(String filename){
         try {
         return new SimpleObjectReader(new ObjectInputStream(new FileInputStream(filename)));
         } catch(IOException e) {     
         return null;
    * Reads a single object from the file and returns it. If there are
    * no more objects in the file (i.e, we have reached the end of file),
    * null is returned null is returned. null is also
    * returned on any I/O error.
    public Object readObject (){
         try {
         return ois.readObject();
         } catch (IOException e) {
         e.printStackTrace();
         return null;
         } catch (ClassNotFoundException e) {
         e.printStackTrace();
         return null;
    * Closes the file when done reading. You should close a reader when
    * you are finished to release the OS resources for use by others.
    public void close (){
         try {
         ois.close();
         catch (IOException e) {}
    * Constructor is private so that only means to create a new reader
    * is through the static method which does error checking.
    private SimpleObjectReader(ObjectInputStream ois){
         this.ois = ois;
    import java.io.*;
    * SimpleObjectWriter is a small class to wrap around the usual
    * ObjectOutputStream to shield you from the exception handling
    * which we haven't yet gotten to in class.
    * <P>It has just three methods of note: one to open a new file for writing,
    * one to write an object to the file, and one to close the
    * the file when done.
    * <P>Here is a simple example that shows using the SimpleObjectWriter
    * to create a new file and write some objects into it:
    * <PRE>
    * SimpleObjectWriter writer =
    * SimpleObjectWriter.openFileForWriting("objects");
    * if (writer == null) {
    * System.out.println("Couldn't open file!");
    * return;
    * writer.writeObject("Here is a string");
    * writer.writeObject("And another one.");
    * writer.writeObject(new Date());
    * writer.close();
    * </PRE>
    * <P>You are free to edit or extend this class, but we don't expect that
    * you should need to make any changes.
    * @version 1.1 15/04/01
    * @author Julie Zelenski
    * @author (touched up by Ian A. Mason)
    public class SimpleObjectWriter {
    private ObjectOutputStream oos;
    * Opens a new file for writing. The filename can either be a relative
    * path, which will be relative to the working directory of the program
    * when started, or an absolute path. If the file can be created, a
    * new SimpleObjectWriter is returned. If the file already exists, this
    * will overwrite its content

    I'm not reading that either, but to help you for next time:
    - use more than 1 sentence to describe your problem
    - only post the RELEVANT code, or a small test program with the same problem if possible.
    At least you formatted it, I'll give you that.
    Cheers,
    Radish21
    PS. I think in this case, posting another (better worded) thread might be a good idea, because no one is going to read this one. In general though, don't :)

  • Problem with JFileChooser when run using Netbeans

    I just want to state that I have NO problem writing the code that brings up this component. My problem is what happens when the JFileChooser component is loaded. My environment is Windows Vista, Java SE 1.6.0. -> Netbeans IDE 5.0. The code I use is as follows:
    public RegexParser()
    JFileChooser openfile = new JFileChooser();
    openfile.showOpenDialog(RegexParser.this);
    int returnVal = openfile.showOpenDialog(RegexParser.this);
    if (returnVal == JFileChooser.APPROVE_OPTION)
    //This code gets the path of the file and uses as a parameter to parse data.
    filename = openfile.getSelectedFile().getPath();
    openfile.setVisible(false);
    ParseData(filename);
    The problem is when I try to select an option from the combobox labeled "Look In:" Every directory I select which is not the root of the drive will display NO FILES even though there are files in that directory.
    Notice: I have also run the same code using the cmd.exe and it works fine. I have also looked at: http://java.sun.com/docs/books/tutorial/uiswing/components/filechooser.html but have found nothing that has helped me.
    Can someone explain what is the problem? Is this a known bug in Netbeans? Is there any code that can be used as a workaround?

    Yes I copied the code to my machine and run it. The example program had problems when I executed using netbeans it had the problem.
    When I executed using Command Prompt there where no problems.

Maybe you are looking for

  • Windows 200 PC with SP4 won't boot after install of iPod software from CD.

    I installed the iPod software from the CD of my new iPod mini. It requested that I reboot the PC, which I did but it never rebooted. It hung and would not even boot in safe mode. After many attempts I booted to the boot console and when throught the

  • Apple Software Update hangs on Windows 7.

    Even after uninstalling iTunes & Apple Software Update, downloading and installing the latest iTunes, still Apple Software Update hangs, see pic: There is no freeze, but the spinning icon keeps on spinning forever unless the process is killed ('stop'

  • IPod touch 4 iOS 5 connection problems

    hi i just downloaded the ios 5.0 gm and the new itunes and when i restored my itouch to 5.0 the wifi stopped working. id type in the password and next to hte name of the network it had the loading sign. But when the wifi icon would finally appear at

  • Quicktime X

    When I click on a video in iphoto, it doesn't automatically play on Quicktime like it used to. I have to drag the video to the QT icon in the dock. I installed a new HD and Snow Leopard, and these videos are from my Time Machine backups. They play fi

  • [S210 Touch] One key recovery not working

    I have a 1.25 year old S210 Ideapad Touch.  I made a 100GB partition with EaseUS and had no problem with onekey recovery.  I tried to merge that empty partition with my C drive using EaseUS software but it did not work saying there were errors.  Afte