NullPointerException in JFileChooser.showOpenDialog() JRE 1.7

Hi all,
In my application, i have used JFileChooser to select a file. When i try to open JFileChooser.showOpenDialog() it throws the following exception. Not sure where i am wrong. Please help me.
Exception:
#Exception in thread "AWT-EventQueue-0" java.lang.NullPointerException
# at sun.awt.shell.Win32ShellFolder2.access$200(Unknown Source)
# at sun.awt.shell.Win32ShellFolder2$1.call(Unknown Source)
# at sun.awt.shell.Win32ShellFolder2$1.call(Unknown Source)
# at java.util.concurrent.FutureTask$Sync.innerRun(Unknown Source)
# at java.util.concurrent.FutureTask.run(Unknown Source)
# at java.util.concurrent.ThreadPoolExecutor.runWorker(Unknown Source)
# at java.util.concurrent.ThreadPoolExecutor$Worker.run(Unknown Source)
# at sun.awt.shell.Win32ShellFolderManager2$ComInvoker$3.run(Unknown Source)
# at java.lang.Thread.run(Unknown Source)
Source Code:
     public File browseFile() {
          UIManager.put("FileChooser.readOnly", Boolean.TRUE);
          if (DEBUG > 4) {
               System.out.println("Initial Dir : " + initialDir);
               System.out.println("Title : " + title);
          JFileChooser jfc = new JFileChooser();
          FileFilter filter = null;
          if (null != extension && extension.trim().length() > 0) {
               if (null != description && description.trim().length() > 0) {
                    filter = new ExtensionFilter(this.description, this.extension);
               } else {
                    filter = new ExtensionFilter(this.extension, this.extension);
               jfc.setFileFilter(filter);
          if (null != title && title.trim().length() > 0) {
               jfc.setDialogTitle(title);
          if (null != initialDir) {
               jfc.setCurrentDirectory(new File(initialDir));
          int returnVal = - 1;
          if (type == JFileChooser.OPEN_DIALOG) {
               returnVal = jfc.showOpenDialog(this);
          } else if (type == JFileChooser.SAVE_DIALOG) {
               returnVal = jfc.showSaveDialog(this);
          if (returnVal == JFileChooser.APPROVE_OPTION) {
               File file = jfc.getSelectedFile();
               setVisible(false);
               return file;
          } else {
               setVisible(false);
               return null;
Thanks for all in Advance.
/dhavan

Sorry, actually i commented that line. Here is the updated code.
     public File browseFile() {
          parent = this;
          UIManager.put("FileChooser.readOnly", Boolean.TRUE);
//          if (DEBUG > 4) {
               System.out.println("Initial Dir : " + initialDir);
               System.out.println("Initial File : " + initialFile);
               System.out.println("Title : " + title);
          try {
               EventQueue.invokeLater( new Runnable() {
                    public void run() {
                         jfc = new JFileChooser();
                         FileFilter filter = null;
                         if (null != extension && extension.trim().length() > 0) {
                              if (null != description && description.trim().length() > 0) {
                                   filter = new ExtensionFilter(description, extension);
                              } else {
                                   filter = new ExtensionFilter(extension, extension);
                              jfc.setFileFilter(filter);
                         if (null != title && title.trim().length() > 0) {
                              jfc.setDialogTitle(title);
                         if (null != initialDir) {
                              jfc.setCurrentDirectory(new File(initialDir));
                    if (type == JFileChooser.OPEN_DIALOG) {
                         System.out.println("JFileChooser.OPEN_DIALOG");
                         returnVal = jfc.showOpenDialog(parent);
                    } else if (type == JFileChooser.SAVE_DIALOG) {
                         System.out.println("JFileChooser.SAVE_DIALOG");
                         returnVal = jfc.showSaveDialog(parent);
          } catch (Exception ex) {
               ex.printStackTrace();
          return null;
          if (returnVal == JFileChooser.APPROVE_OPTION) {
               File file = jfc.getSelectedFile();
               return file;
          } else {
               return null;
     }Exception:-
#Exception in thread "AWT-EventQueue-0" java.lang.NullPointerException
#     at sun.awt.shell.Win32ShellFolderManager2.createShellFolder(Unknown Source)
#     at sun.awt.shell.Win32ShellFolderManager2.getRecent(Unknown Source)
#     at sun.awt.shell.Win32ShellFolderManager2.get(Unknown Source)
#     at sun.awt.shell.ShellFolder.get(Unknown Source)
#     at sun.swing.WindowsPlacesBar.<init>(Unknown Source)
#     at com.sun.java.swing.plaf.windows.WindowsFileChooserUI.updateUseShellFolder(Unknown Source)
#     at com.sun.java.swing.plaf.windows.WindowsFileChooserUI.installComponents(Unknown Source)
#     at javax.swing.plaf.basic.BasicFileChooserUI.installUI(Unknown Source)
#     at com.sun.java.swing.plaf.windows.WindowsFileChooserUI.installUI(Unknown Source)
#     at javax.swing.JComponent.setUI(Unknown Source)
#     at javax.swing.JFileChooser.updateUI(Unknown Source)
#     at javax.swing.JFileChooser.setup(Unknown Source)
#     at javax.swing.JFileChooser.<init>(Unknown Source)
#     at javax.swing.JFileChooser.<init>(Unknown Source)
#     at com.marimba.ncp.apps.editor.SwingFileChooser$1.run(SwingFileChooser.java:59)
#     at java.awt.event.InvocationEvent.dispatch(Unknown Source)
#     at java.awt.EventQueue.dispatchEventImpl(Unknown Source)
#     at java.awt.EventQueue.access$000(Unknown Source)
#     at java.awt.EventQueue$1.run(Unknown Source)
#     at java.awt.EventQueue$1.run(Unknown Source)
#     at java.security.AccessController.doPrivileged(Native Method)
#     at java.security.AccessControlContext$1.doIntersectionPrivilege(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)

Similar Messages

  • NullPointerException in JFileChooser

    Hello,
    I have a method which shows a JFileChooser to select a save name. After click on the dialog's OK button, sometimes it throws NullPointerException.
    I have checked the thread, and everything runs in EDT, so this should not be the problem.
    The calling code is
    public File getSelectedFile() {
    chooser = new JFileChooser(prefs.get(Configuration.KEY_LAST_SAVED_DIR, null));
    chooser.setSelectedFile(new File(defaultFileName));
    for(ExtensionFileFilter f : fileTypes){
    chooser.addChoosableFileFilter(f);
    if (defaultFilter == null) {
    chooser.setFileFilter(chooser.getAcceptAllFileFilter());
    } else {
    chooser.setFileFilter(defaultFilter);
    // That's where it happens
    int returnVal = chooser.showSaveDialog(parentComponent);
    prefs.put(Configuration.KEY_LAST_SAVED_DIR,chooser.getCurrentDirectory().getAbsolutePath());
    return chooser.getSelectedFile();
    Can you help me spot where the problem is?
    The stack trace is below.
    Thanks for any suggestions.
    Karl
    Exception occurred during event dispatching:
    java.lang.NullPointerException
    at javax.swing.JComponent.repaint(JComponent.java:4728)
    at sun.swing.FilePane$2.repaintListSelection(FilePane.java:114)
    at sun.swing.FilePane$2.repaintSelection(FilePane.java:104)
    at sun.swing.FilePane$2.focusLost(FilePane.java:99)
    at java.awt.AWTEventMulticaster.focusLost(AWTEventMulticaster.java:213)
    at java.awt.Component.processFocusEvent(Component.java:5930)
    at java.awt.Component.processEvent(Component.java:5794)
    at java.awt.Container.processEvent(Container.java:2058)
    at java.awt.Component.dispatchEventImpl(Component.java:4410)
    at java.awt.Container.dispatchEventImpl(Container.java:2116)
    at java.awt.Component.dispatchEvent(Component.java:4240)
    at java.awt.KeyboardFocusManager.redispatchEvent(KeyboardFocusManager.java:1848)
    at java.awt.DefaultKeyboardFocusManager.typeAheadAssertions(DefaultKeyboardFocusManager.java:878)
    at java.awt.DefaultKeyboardFocusManager.dispatchEvent(DefaultKeyboardFocusManager.java:551)
    at java.awt.Component.dispatchEventImpl(Component.java:4282)
    at java.awt.Container.dispatchEventImpl(Container.java:2116)
    at java.awt.Component.dispatchEvent(Component.java:4240)
    at java.awt.EventQueue.dispatchEvent(EventQueue.java:599)
    at java.awt.EventDispatchThread.pumpOneEventForFilters(EventDispatchThread.java:273)
    at java.awt.EventDispatchThread.pumpEventsForFilter(EventDispatchThread.java:183)
    at java.awt.EventDispatchThread.pumpEventsForFilter(EventDispatchThread.java:177)
    at java.awt.Dialog$1.run(Dialog.java:1039)
    at java.awt.Dialog$3.run(Dialog.java:1091)
    at java.security.AccessController.doPrivileged(Native Method)
    at java.awt.Dialog.show(Dialog.java:1089)
    at javax.swing.JFileChooser.showDialog(JFileChooser.java:723)
    at javax.swing.JFileChooser.showSaveDialog(JFileChooser.java:651)
    at io.FileSaver.getSelectedFile(FileSaver.java:141)
    at io.SaverManager.<init>(SaverManager.java:96)
    at io.SaverHolder$SaveSelector.actionPerformed(SaverHolder.java:153)
    at javax.swing.AbstractButton.fireActionPerformed(AbstractButton.java:1995)
    at javax.swing.AbstractButton$Handler.actionPerformed(AbstractButton.java:2318)
    at javax.swing.DefaultButtonModel.fireActionPerformed(DefaultButtonModel.java:387)
    at javax.swing.DefaultButtonModel.setPressed(DefaultButtonModel.java:242)
    at javax.swing.plaf.basic.BasicButtonListener.mouseReleased(BasicButtonListener.java:236)
    at java.awt.Component.processMouseEvent(Component.java:6038)
    at javax.swing.JComponent.processMouseEvent(JComponent.java:3260)
    at java.awt.Component.processEvent(Component.java:5803)
    at java.awt.Container.processEvent(Container.java:2058)
    at java.awt.Component.dispatchEventImpl(Component.java:4410)
    at java.awt.Container.dispatchEventImpl(Container.java:2116)
    at java.awt.Component.dispatchEvent(Component.java:4240)
    at java.awt.LightweightDispatcher.retargetMouseEvent(Container.java:4322)
    at java.awt.LightweightDispatcher.processMouseEvent(Container.java:3986)
    at java.awt.LightweightDispatcher.dispatchEvent(Container.java:3916)
    at java.awt.Container.dispatchEventImpl(Container.java:2102)
    at java.awt.Window.dispatchEventImpl(Window.java:2429)
    at java.awt.Component.dispatchEvent(Component.java:4240)
    at java.awt.EventQueue.dispatchEvent(EventQueue.java:599)
    at java.awt.EventDispatchThread.pumpOneEventForFilters(EventDispatchThread.java:273)
    at java.awt.EventDispatchThread.pumpEventsForFilter(EventDispatchThread.java:183)
    at java.awt.EventDispatchThread.pumpEventsForHierarchy(EventDispatchThread.java:173)
    at java.awt.EventDispatchThread.pumpEvents(EventDispatchThread.java:168)
    at java.awt.EventDispatchThread.pumpEvents(EventDispatchThread.java:160)
    at java.awt.EventDispatchThread.run(EventDispatchThread.java:121)

    My first answer was wrong because the constructor which can handle a null input is the one taking a File. But from the prefs I get a String... So the I need to check first if the string is null and make a File out of it...
    About your idea to use the debugger, I can see where the problem happens (see also the stack trace above). It's when the dialog is showing (Dialog.show has been called) and then, after pressing OK, the Component gets repainted
    java.lang.NullPointerException
    at javax.swing.JComponent.repaint(JComponent.java:4728)
    Unfortunately the problem is only showing once in a while, so it's hard to test solutions...
    Thanks anyway
    Karl

  • NullException when setUI on JFileChooser

    I wrote a sub class of MetalFileChooserUI, and set it for my file chooser. but when i show the file chooser dialog, the icons for the files is disappeared. if i click the file list item, NullException occur. why?
    MY code:
    public class MyChooser extends JFileChooser {
    public MyChooser(String file) {
    super(file);
    setUI(new MyChooserUI());
    public class MyChooserUI extends MetalFileChooserUI {
    public MyChooserUI(JFileChooser fc) {
    super(fc);
    Error Message:
    Exception occurred during event dispatching:
    java.lang.NullPointerException
         at javax.swing.plaf.metal.MetalFileChooserUI$FileRenderer.getListCellRendererComponent(MetalFileChooserUI.java:536)
         at javax.swing.plaf.basic.BasicListUI.paintCell(BasicListUI.java:87)
         at com.incors.plaf.kunststoff.KunststoffListUI.paintCell(KunststoffListUI.java:91)
         at javax.swing.plaf.basic.BasicListUI.paint(BasicListUI.java:149)
         at com.incors.plaf.kunststoff.KunststoffListUI.update(KunststoffListUI.java:72)
         at javax.swing.JComponent.paintComponent(JComponent.java:395)
         at javax.swing.JComponent.paint(JComponent.java:687)
         at javax.swing.JComponent.paintChildren(JComponent.java:498)
         at javax.swing.JComponent.paint(JComponent.java:696)
         at javax.swing.JViewport.paint(JViewport.java:668)
         at javax.swing.JComponent.paintWithBuffer(JComponent.java:3878)
         at javax.swing.JComponent._paintImmediately(JComponent.java:3821)
         at javax.swing.JComponent.paintImmediately(JComponent.java:3672)
         at javax.swing.RepaintManager.paintDirtyRegions(RepaintManager.java:370)
         at javax.swing.SystemEventQueueUtilities$ComponentWorkRequest.run(SystemEventQueueUtilities.java:124)
         at java.awt.event.InvocationEvent.dispatch(InvocationEvent.java:154)
         at java.awt.EventQueue.dispatchEvent(EventQueue.java:337)
         at java.awt.EventDispatchThread.pumpOneEventForHierarchy(EventDispatchThread.java:131)
         at java.awt.EventDispatchThread.pumpEventsForHierarchy(EventDispatchThread.java:98)
         at java.awt.Dialog.show(Dialog.java:380)
         at javax.swing.JFileChooser.showDialog(JFileChooser.java:614)
         at javax.swing.JFileChooser.showOpenDialog(JFileChooser.java:517)

    I think JFileChooser is a platform independent solution and Network Neighbourhood is a Windows implementation.
    You can use use a FileDialog, I think it uses the Window native open dialog.
    Use code something like this:
    File Dialog fileDialog = new FileDialog( parent frame );
    fileDialog.setMode(FileDialog.LOAD);
    fileDialog.show();
    if (fileDialog.getFile() == null)
    return;
    File file = new File( fileDialog.getDirectory(), fileDialog.getFile() );

  • How to close JFileChooser dialog only while using ESC key ?

    Hi All,
    I am using a Frame and from this frame i am calling the JFileChooser via a JButton.
    and using JFileChooser ShowOpenDialog() for open and close .
    while doing ESC operation my Main Frame is getting closed with JFileChooser dialog.
    Can i close only JFileChooser dialog while doing ESCAPE key operation.
    I Have Escape key function in Main Frame file and JFileChooser file( EscKeyEventActionIntialization)
    But while debuging i am not able to catch the esc key action inside EscKeyEventActionIntialization.
    I have attached the code, please suggest me , if i need to do any change .
    * To change this template, choose Tools | Templates
    * and open the template in the editor.
    package MainPackage;
    import javax.swing.filechooser.*;
    import java.awt.event.ActionEvent;
    import java.awt.event.KeyEvent;
    import javax.swing.*;
    public class SourceSettings extends javax.swing.JDialog{
        JDialog dialog;
        private javax.swing.JFileChooser jFileChooser1;
        MainFile  mainFile;
        ImageIcon icon = new ImageIcon(getClass().getResource("/Resource/mchpIcon.GIF"));
        /** Creates new form SourceSetting */
        public SourceSettings(MainFile  pMPFS) {
            dialog = new JDialog();
            dialog.setDefaultCloseOperation(JDialog.DISPOSE_ON_CLOSE);
            mainFile = pMPFS;
            jFileChooser1 = new javax.swing.JFileChooser();
            dialog.add(jFileChooser1);
            EscKeyEventActionIntialization();
            jFileChooser1.setDialogTitle("Browse For Folder");
            jFileChooser1.setFont(new java.awt.Font("Microsoft Sans Serif", 0, 11)); // NOI18N
            jFileChooser1.setName("Browse For Folder"); // NOI18N
        public String getDirctoryPath()
            int retval = jFileChooser1.showOpenDialog(dialog);
            dialog.setVisible(true);
            if(retval  == JFileChooser.APPROVE_OPTION)
                return jFileChooser1.getSelectedFile().getAbsolutePath().toString();
            else
                dialog.setVisible(false);
                dialog.dispose();
                return null;
        public String getParentDirctoryPath()
            return jFileChooser1.getCurrentDirectory().getAbsolutePath().toString();
        public String getOutputDirctoryPath()
            if(jFileChooser1.showOpenDialog(mainMpfs)  == JFileChooser.APPROVE_OPTION)
               return jFileChooser1.getCurrentDirectory().getAbsolutePath().toString();
            else
               dialog.dispose();
               return null;
        private void EscKeyEventActionIntialization()
            Action  ESCactionListener = new AbstractAction () {
              public void actionPerformed(ActionEvent actionEvent) {
                dialog.setVisible(false);
                dialog.dispose();
            KeyStroke stroke = KeyStroke.getKeyStroke(KeyEvent.VK_ESCAPE, 0, true);
            JComponent comp = dialog.getRootPane();
            comp.getInputMap(JComponent.WHEN_IN_FOCUSED_WINDOW).put(stroke, "ESCAPE");
            ActionMap actionMap = comp.getActionMap();
            actionMap.put("ESCAPE", ESCactionListener);
    }

    You have a class that extends JDialog and has a JDialog member variable (very confusing), and no main(...) method. How is the class used as a JDialog?
    To get better help sooner, post a SSCCE that clearly demonstrates your problem. Note that this should be executable and should not contain any extraneous code.
    db

  • JFileChooser problem on MAC OS

    In JavaFX UI on click of Browse button, I am using JFileChooser to open the file system. Below is the piece of code which I am executing and the exception I am getting:
    Later I used DirectoryChooser. This is working fine but the pop-up is always coming behind javafx applet when started in browser.
    Note: This is working fine if we run as stand alone application.
    JFileChooser chooser = new JFileChooser(new File("/Volumes/"));
    chooser.setFileSelectionMode(JFileChooser.DIRECTORIES_ONLY);
    int result = chooser.showOpenDialog(null);
    if (result == JFileChooser.APPROVE_OPTION) {
    System.out.println("selectedFile: "+chooser.getSelectedFile());
    //tfFileSelected.setText(getParent(chooser.getSelectedFile()));
    2013-03-04 10:16:40.480 java[15576:5803] *** WARNING: Method userSpaceScaleFactor in class NSView is deprecated on 10.7 and later. It should not be used in new applications. Use convertRectToBacking: instead.
    2013-03-04 10:16:42.614 java[15576:707] [JRSAppKitAWT markAppIsDaemon]: Process manager already initialized: can't fully enable headless mode.
    Glass detected outstanding Java exception at -[GlassViewDelegate sendJavaMouseEvent:]:src/com/sun/mat/ui/GlassViewDelegate.m:541
    Exception in thread "AWT-AppKit" java.awt.HeadlessException
         at java.awt.GraphicsEnvironment.checkHeadless(GraphicsEnvironment.java:207)
         at java.awt.Window.<init>(Window.java:535)
         at java.awt.Frame.<init>(Frame.java:420)
         at java.awt.Frame.<init>(Frame.java:385)
         at javax.swing.SwingUtilities$SharedOwnerFrame.<init>(SwingUtilities.java:1759)
         at javax.swing.SwingUtilities.getSharedOwnerFrame(SwingUtilities.java:1834)
         at javax.swing.JOptionPane.getRootFrame(JOptionPane.java:1697)
         at javax.swing.JOptionPane.getWindowForComponent(JOptionPane.java:1638)
         at javax.swing.JFileChooser.createDialog(JFileChooser.java:785)
         at javax.swing.JFileChooser.showDialog(JFileChooser.java:732)
         at javax.swing.JFileChooser.showOpenDialog(JFileChooser.java:639)
         at samplebrowse.SampleBrowse$1.handle(SampleBrowse.java:46)
         at samplebrowse.SampleBrowse$1.handle(SampleBrowse.java:31)
         at com.sun.javafx.event.CompositeEventHandler.dispatchBubblingEvent(CompositeEventHandler.java:69)
         at com.sun.javafx.event.EventHandlerManager.dispatchBubblingEvent(EventHandlerManager.java:217)
         at com.sun.javafx.event.EventHandlerManager.dispatchBubblingEvent(EventHandlerManager.java:170)
         at com.sun.javafx.event.CompositeEventDispatcher.dispatchBubblingEvent(CompositeEventDispatcher.java:38)
         at com.sun.javafx.event.BasicEventDispatcher.dispatchEvent(BasicEventDispatcher.java:37)
         at com.sun.javafx.event.EventDispatchChainImpl.dispatchEvent(EventDispatchChainImpl.java:92)
         at com.sun.javafx.event.BasicEventDispatcher.dispatchEvent(BasicEventDispatcher.java:35)
         at com.sun.javafx.event.EventDispatchChainImpl.dispatchEvent(EventDispatchChainImpl.java:92)
         at com.sun.javafx.event.EventUtil.fireEventImpl(EventUtil.java:53)
         at com.sun.javafx.event.EventUtil.fireEvent(EventUtil.java:28)
         at javafx.event.Event.fireEvent(Event.java:171)
         at javafx.scene.Node.fireEvent(Node.java:6863)
         at javafx.scene.control.Button.fire(Button.java:179)
         at com.sun.javafx.scene.control.behavior.ButtonBehavior.mouseReleased(ButtonBehavior.java:193)
         at com.sun.javafx.scene.control.skin.SkinBase$4.handle(SkinBase.java:336)
         at com.sun.javafx.scene.control.skin.SkinBase$4.handle(SkinBase.java:329)
         at com.sun.javafx.event.CompositeEventHandler.dispatchBubblingEvent(CompositeEventHandler.java:64)
         at com.sun.javafx.event.EventHandlerManager.dispatchBubblingEvent(EventHandlerManager.java:217)
         at com.sun.javafx.event.EventHandlerManager.dispatchBubblingEvent(EventHandlerManager.java:170)
         at com.sun.javafx.event.CompositeEventDispatcher.dispatchBubblingEvent(CompositeEventDispatcher.java:38)
         at com.sun.javafx.event.BasicEventDispatcher.dispatchEvent(BasicEventDispatcher.java:37)
         at com.sun.javafx.event.EventDispatchChainImpl.dispatchEvent(EventDispatchChainImpl.java:92)
         at com.sun.javafx.event.BasicEventDispatcher.dispatchEvent(BasicEventDispatcher.java:35)
         at com.sun.javafx.event.EventDispatchChainImpl.dispatchEvent(EventDispatchChainImpl.java:92)
         at com.sun.javafx.event.BasicEventDispatcher.dispatchEvent(BasicEventDispatcher.java:35)
         at com.sun.javafx.event.EventDispatchChainImpl.dispatchEvent(EventDispatchChainImpl.java:92)
         at com.sun.javafx.event.EventUtil.fireEventImpl(EventUtil.java:53)
         at com.sun.javafx.event.EventUtil.fireEvent(EventUtil.java:33)
         at javafx.event.Event.fireEvent(Event.java:171)
         at javafx.scene.Scene$MouseHandler.process(Scene.java:3324)
         at javafx.scene.Scene$MouseHandler.process(Scene.java:3164)
         at javafx.scene.Scene$MouseHandler.access$1900(Scene.java:3119)
         at javafx.scene.Scene.impl_processMouseEvent(Scene.java:1559)
         at javafx.scene.Scene$ScenePeerListener.mouseEvent(Scene.java:2261)
         at com.sun.javafx.tk.quantum.GlassViewEventHandler.handleMouseEvent(GlassViewEventHandler.java:228)
         at com.sun.glass.ui.View.handleMouseEvent(View.java:528)
         at com.sun.glass.ui.View.notifyMouse(View.java:922)
    2013-03-04 10:16:44.769 java[15576:707] unrecognized type is -2
    2013-03-04 10:16:44.770 java[15576:707] *** Assertion failure in -[NSEvent _initWithCGSEvent:eventRef:], /SourceCache/AppKit/AppKit-1187.34/AppKit.subproj/NSEvent.m:1348
    2013-03-04 10:16:44.770 java[15576:707] Invalid parameter not satisfying: cgsEvent.type > 0 && cgsEvent.type <= kCGSLastEventType
    2013-03-04 10:16:44.771 java[15576:707] (
         0 CoreFoundation 0x00007fff952af0a6 __exceptionPreprocess + 198
         1 libobjc.A.dylib 0x00007fff93fc13f0 objc_exception_throw + 43
         2 CoreFoundation 0x00007fff952aeee8 +[NSException raise:format:arguments:] + 104
         3 Foundation 0x00007fff8af8e6a2 -[NSAssertionHandler handleFailureInMethod:object:file:lineNumber:description:] + 189
         4 AppKit 0x00007fff8c8da56c -[NSEvent _initWithCGSEvent:eventRef:] + 2782
         5 AppKit 0x00007fff8cb5b3ea +[NSEvent eventWithCGEvent:] + 243
         6 libglass.dylib 0x0000000163f4c02f listenTouchEvents + 31
         7 CoreGraphics 0x00007fff919b20d9 processEventTapData + 150
         8 CoreGraphics 0x00007fff919b1f2c _CGYPostEventTapData + 189
         9 CoreGraphics 0x00007fff9191155d _XPostEventTapData + 107
         10 CoreGraphics 0x00007fff91911655 CGYEventTap_server + 106
         11 CoreGraphics 0x00007fff919b201a eventTapMessageHandler + 30
         12 CoreFoundation 0x00007fff9521e410 __CFMachPortPerform + 288
         13 CoreFoundation 0x00007fff9521e2d9 __CFRUNLOOP_IS_CALLING_OUT_TO_A_SOURCE1_PERFORM_FUNCTION__ + 41
         14 CoreFoundation 0x00007fff9521e019 __CFRunLoopDoSource1 + 153
         15 CoreFoundation 0x00007fff9525119f __CFRunLoopRun + 1775
         16 CoreFoundation 0x00007fff952506b2 CFRunLoopRunSpecific + 290
         17 HIToolbox 0x00007fff8db930a4 RunCurrentEventLoopInMode + 209
         18 HIToolbox 0x00007fff8db92e42 ReceiveNextEventCommon + 356
         19 HIToolbox 0x00007fff8db92cd3 BlockUntilNextEventMatchingListInMode + 62
         20 AppKit 0x00007fff8c7fb613 _DPSNextEvent + 685
         21 AppKit 0x00007fff8c7faed2 -[NSApplication nextEventMatchingMask:untilDate:inMode:dequeue:] + 128
         22 AppKit 0x00007fff8c7f2283 -[NSApplication run] + 517
         23 libglass.dylib 0x0000000163f394e9 -[GlassApplication runLoop:] + 777
         24 Foundation 0x00007fff8b014677 __NSThreadPerformPerform + 225
         25 CoreFoundation 0x00007fff9522e101 __CFRUNLOOP_IS_CALLING_OUT_TO_A_SOURCE0_PERFORM_FUNCTION__ + 17
         26 CoreFoundation 0x00007fff9522da25 __CFRunLoopDoSources0 + 245
         27 CoreFoundation 0x00007fff95250dc5 __CFRunLoopRun + 789
         28 CoreFoundation 0x00007fff952506b2 CFRunLoopRunSpecific + 290
         29 java 0x0000000109e274bc CreateExecutionEnvironment + 871
         30 java 0x0000000109e21cac JLI_Launch + 1952
         31 java 0x0000000109e27819 main + 101
         32 java 0x0000000109e21504 start + 52
    )

    "Later I used DirectoryChooser. This is working fine but the pop-up is always coming behind javafx applet when started in browser. Note: This is working fine if we run as stand alone applicationYou should file a bug/feature request about this against the Runtime project:
    http://javafx-jira.kenai.com
    Exception in thread "AWT-AppKit" java.awt.HeadlessExceptionSee:
    http://javafx-jira.kenai.com/browse/RT-20784 "Mac: Headless environment issue, MacOSX"
    The above issue discusses some potential workarounds which may (or may not) work in your situation.
    Try the latest 8-ea build (available at http://jdk8.java.net/download.html).
    The graphics environment is no longer forced to be headless in the java 8 trunk (the jira case I linked is closed as fixed), but it may take a week or two for the fix to propagate to the jdk8 early access download page.
    Also note that this kind of call from a JavaFX application to a Swing component isn't really a supported configuration (embedding JavaFX in a JFXPanel in a Swing application is supported, but other forms of interaction between JavaFX and Swing such as JavaFX opening Swing dialogs are not). That's not to say that it might not work, it's just that you shouldn't expect it to work now or continue to work in the future (especially in an applet deployment context where the window handling is more complex for the underlying frameworks due to the browser embedding). Further facilities to ease Swing and JavaFX integration are planned for JavaFX 8 (http://javafx-jira.kenai.com/browse/RT-12100 "Swing components inside JavaFX"), but I don't know if it would mean that the scenario you are trying to achieve would be supported.
    A further alternative you might have would be to deploy your application as a Swing application rather than a JavaFX application and wrap your JavaFX content in a JFXPanel. It is likely that opening a Swing JFileChooser would work in such a mixed code scenario, though I have not tried it.

  • JFileChooser blocks all JFrames

    I believe something like this was asked before already, but I could not find a satisfactory solution.
    Situation:
    I have X JFrames open. Each frame has a "Browse" button and a "New Window" button, and some content like an image or text. Clicking "Browse" opens a new JFileChooser, and "New Window" opens a new JFrame like all the others.
    Problem:
    Whenever I click "Browse" in one of the JFrames, I cannot interact with ANY JFrame until the JFileChooser is closed. Clicking buttons has no effect, and no ActionEvents are delivered to either parent window or other windows. Similarly, if the program cannot open the file chosen it displays an error dialog which behaves in exactly the same way, blocking all windows and not just the parent window like would be logical and acceptable.
    Failed solution:
    In the beginning of the actionPerformed method I start a new thread to actually handle the ActionEvent. I have verified that the actionPerformed method finishes before the JFileChooser is closed, so I know the opening of the filechooser is not blocking the event dispatching thread. I also ran the SwingUtilities check to see whether the JFileChooser opening was running in the event dispatching thread and the result was false.
    As far as I can see everything should be ok, but still all my JFrames remain blocked if any of them opens up a JFileChooser or a message window.
    Can anyone help?

    The dialog created by JFileChooser.showOpenDialog() is made modal
    on purpose, so that the return value can be retrieved in a single
    threaded flow without having to set listeners etc.
    You can embed a JFileChooser in your own JDialog and not make it
    modal if you want to. Add a PropertyChangeListener to catch the
    APPROVE_SELECTION and CANCEL_SELECTION events, or override
    the approveSelection() and cancelSelection() methods.
    Leif Samuelsson
    Java Swing Team
    Sun Microsystems, Inc.

  • Help ! JCheckBox in JFileChooser ??

    hi..
    how will include a JCheckBox in A JFileChooser.showOpenDialog ?? my requirement is to create a Read only check Box in the showOpenDialog box .. is that possible.. if so please do help..
    Thanking you..
    rG.

    Quickest would be to sub JFileChooser.... :)
    It can also be added to a panel, so that is a possible solve as well...

  • JfileChooser � choose only directories

    How can one in Java[b] CHOOSE (NOT just view) in OpenDialog (via Jfilechooser showOpenDialog method) ONLY DIRECTORIES.
    The desired Filechooser should be able to open directories as well as choose them (as selected) and view directories and files as well. It should be possible to choose (as selected) also directories that are empty or comprise just other subdirectories and no files. One solution could be to add a 3rd button labeled �select directory� but I did not find out how to do it.
    Could someone help me ?
    Thank you in advance.
    Lubos.

    fc.setFileSelectionMode(JFileChooser.DIRECTORIES_ONLY);
    How to Use File Choosers

  • Errors when loading an object

    I have written code to load in an object but this keeps giving me exceptions when i run the code to try and display the data from the object read in. I get a java.lang.NullPointerException at line 80 in cFaceRecEDetails.java My code is below:
    Thanks
    //--- cFaceRecGUIMain.java ---
    //--- Edmund Smith 23/08/04 ---
    //--- The GUI for the face recognition sofware contains buttons and ---
    //--- display area for an image of a face ---
    import java.awt.*;
    import java.awt.image.*;
    import java.awt.event.*;
    import java.io.*;
    import javax.swing.*;
    import javax.swing.border.*;
    public class cFaceRecGUIMain extends JFrame implements ActionListener {
    //Create menu bar items
    private JMenuItem jmiLoadPicture, jmiExit, jmiEdit;
    //Recognize Button
    private JButton jbtRecognize;
    //Labels with info about picture
    private String lblName, lblDOB, lblNI, lblStaffID;
    //Panel to hold an image
    private ImagePanel imagePanel = new ImagePanel();
    //File Chooser
    JFileChooser jFileChooser = new JFileChooser();
    //BitmapReader
    //cGetBytes getBytes = new cGetBytes();
    //Face database
    cFaceRecData faceDatabase = new cFaceRecData();
    //Set default window sizes
    final int xSize = 600;
    final int ySize = 400;
    //Array for holding pixels
    int pixels[];
    //Labels for menu items
    final String lbljmiLoadPicture = "Load Picture for recogniton";
    final String lbljmiExit = "Exit";
    final String lbljmiEdit = "Edit face database";
    //Create the frame to enter details about people
    cFaceRecGUIEDetails enterDetailsFrame = new cFaceRecGUIEDetails();
    //BitmapReader
    cGetBytes getImageBytes = new cGetBytes();
    //Main method
    public static void main(String[] args)
    cFaceRecGUIMain programFrame = new cFaceRecGUIMain();
    programFrame.pack();
    programFrame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    programFrame.setTitle("Face Recognizer");
    programFrame.setSize(600, 400);
    programFrame.setVisible(true);
    //Constructor
    public cFaceRecGUIMain() {
    //Initialize menu bar
    JMenuBar jmb = new JMenuBar();
    setJMenuBar(jmb);
    //Add menus
    JMenu fileMenu = new JMenu("File");
    fileMenu.setMnemonic('F');
    jmb.add(fileMenu);
    JMenu faceMenu = new JMenu("Face");
    fileMenu.setMnemonic('A');
    jmb.add(faceMenu);
    JMenu helpMenu = new JMenu("Help");
    fileMenu.setMnemonic('H');
    jmb.add(helpMenu);
    //Add menu items
    fileMenu.add(jmiLoadPicture =
    new JMenuItem(lbljmiLoadPicture, 'L'));
    fileMenu.addSeparator();
    fileMenu.add(jmiExit = new JMenuItem(lbljmiExit, 'X'));
    faceMenu.add(jmiEdit = new JMenuItem(lbljmiEdit, 'E'));
    //Set keyboard accelerators
    jmiExit.setAccelerator(
    KeyStroke.getKeyStroke(KeyEvent.VK_E, ActionEvent.CTRL_MASK));
    jmiLoadPicture.setAccelerator(
    KeyStroke.getKeyStroke(KeyEvent.VK_L, ActionEvent.CTRL_MASK));
    //Set up new panel
    imagePanel.setBorder(new TitledBorder("Face"));
    //Lay components on panel
    imagePanel.setImageIcon(new ImageIcon("C:/Documents and Settings/" +
    "Edmund Smith/My Documents/aface.bmp"));
    imagePanel.add(jbtRecognize = new JButton("Recognize"),
    BorderLayout.SOUTH);
    setTitle("Face Recognizer");
    //Labels to hold info
    JPanel lblsAboutImagePanel = new JPanel();
    lblsAboutImagePanel.setBorder(new TitledBorder("Details"));
    lblsAboutImagePanel.setLayout(new GridLayout(4, 2));
    lblsAboutImagePanel.add(new JLabel("Name"));
    lblsAboutImagePanel.add(new JLabel(lblName));
    lblsAboutImagePanel.add(new JLabel("DOB"));
    lblsAboutImagePanel.add(new JLabel(lblDOB));
    lblsAboutImagePanel.add(new JLabel("National insurance number"));
    lblsAboutImagePanel.add(new JLabel(lblNI));
    lblsAboutImagePanel.add(new JLabel("Staff ID"));
    lblsAboutImagePanel.add(new JLabel(lblStaffID));
    //Add the different panels to the frame
    getContentPane().setLayout(new BorderLayout());
    getContentPane().add(imagePanel, BorderLayout.WEST);
    getContentPane().add(lblsAboutImagePanel, BorderLayout.CENTER);
    //Register listeners
    jmiExit.addActionListener(this);
    jmiLoadPicture.addActionListener(this);
    jmiEdit.addActionListener(this);
    //Create the frame where you can enter the details of a person
    enterDetailsFrame.pack();
    enterDetailsFrame.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
    enterDetailsFrame.setTitle("Set up database");
    enterDetailsFrame.setSize(xSize, ySize);
    class edfClosingListener extends WindowAdapter {
    public void windowClosing(WindowEvent e) {
    //Check to see if the record has been changed
    if (enterDetailsFrame.isRecordModified)
    JOptionPane.showConfirmDialog(
    null,
    "Do you want to save changes to this record?",
    "Face datbase",
    JOptionPane.YES_NO_CANCEL_OPTION);
    if (enterDetailsFrame.newPeople.size() > 0)
    //create a temporary array to store the new people
    person[] newPersons = new
    person[enterDetailsFrame.newPeople.size()];
    //Copy the people in the vector to the array
    person tempPerson;
    for (int i = 0; i < newPersons.length; i++)
    tempPerson =
    (person)enterDetailsFrame.newPeople.elementAt(i);
    newPersons.path = tempPerson.path;
    newPersons.personsName = tempPerson.personsName;
    newPersons.personsDOB = tempPerson.personsDOB;
    newPersons.personsNI = tempPerson.personsNI;
    newPersons.personsStaffID = tempPerson.personsStaffID;
    //Create new database
    allPeople outPeople =
    new allPeople(enterDetailsFrame.peopleInfo, newPersons);
    //Save the database with the added records
    enterDetailsFrame.faceDatabase.saveDatabase(outPeople);
    else
    //Save the database with the same number of records
    enterDetailsFrame.faceDatabase.saveDatabase(
    enterDetailsFrame.peopleInfo);
    //Set the actions to happen when windows are closed
    enterDetailsFrame.addWindowListener(new edfClosingListener());
    closeWindow closeMainFrame = new closeWindow();
    addWindowListener(closeMainFrame);
    public void actionPerformed(ActionEvent e)
    String actionCommand = e.getActionCommand();
    if (e.getSource() instanceof JMenuItem) {
    if (lbljmiExit.equals(actionCommand))
    System.exit(0);
    else if (lbljmiLoadPicture.equals(actionCommand))
    open();
    else if (lbljmiEdit.equals(actionCommand)) {
    enterDetailsFrame.setVisible(true);
    //No records have been modified
    enterDetailsFrame.isRecordModified = false;
    //Open a file
    private void open() {
    if (jFileChooser.showOpenDialog(this) == JFileChooser.APPROVE_OPTION)
    try {
    //Get the file name
    String fileName = jFileChooser.getSelectedFile().getPath();
    //Display the image
    ImageIcon imagei = new ImageIcon(fileName);
    imagePanel.setImageIcon(imagei);
    //Set size of array for holiding bytes in the image
    pixels =
    new int[51 * 55];
    //Get the pixels
    // getBytes.getBMPImage(new FileInputStream(new File(fileName)), pixels);
    catch (Exception e) {
    System.out.print(e);
    class ImagePanel extends JPanel {
    //Label to hold the face
    private JLabel jlblFace = new JLabel();
    //Constructor
    public ImagePanel() {
    setLayout(new BorderLayout());
    add(jlblFace, BorderLayout.CENTER);
    //Set image and show it
    public void setImageIcon(ImageIcon icon) {
    jlblFace.setIcon(icon);
    Dimension dimension =
    new Dimension(icon.getIconWidth(), icon.getIconHeight());
    jlblFace.setPreferredSize(dimension);
    //--- cFaceRecGUIEDetails.java ---
    //--- Edmund Smith 06/10/04 ---
    //--- Allows the user to enter details about a person, view the ---
    //--- database and add people to the database ---
    import javax.swing.*;
    import java.awt.*;
    import java.awt.event.*;
    import javax.swing.border.*;
    import java.util.*;
    class cFaceRecGUIEDetails extends JFrame implements KeyListener, ActionListener
    //Buttons to navigate the database
    private JButton jbtPrevious, jbtNext;
    //Button to load a face
    private JButton jbtLoadFace;
    //Fields to display info about the person
    private JTextField jtfName, jtfDOB, jtfNI, jtfStaffID;
    //Panel to hold an image
    private ImagePanel imagePanel = new ImagePanel();
    //File Chooser
    private JFileChooser jFileChooser = new JFileChooser();
    //Variable to tell whether record has been modified
    boolean isRecordModified = false;
    //Tells which record current being veiwed/changed
    int currentRecord = 0;
    //Stores new people to be added to database
    Vector newPeople = new Vector();
    //Face database
    cFaceRecData faceDatabase;
    public allPeople peopleInfo;
    //Default Constructor
    public cFaceRecGUIEDetails()
    //Get the face database
    faceDatabase = new cFaceRecData();
    peopleInfo = faceDatabase.restoreDatabase();
    //Panel to hold two buttons to navigate the database
    JPanel jpButtons = new JPanel();
    //Add navigation buttons to panel
    jpButtons.setLayout(new FlowLayout());
    jpButtons.add(jbtPrevious = new JButton());
    jpButtons.add(jbtNext = new JButton());
    //Set button text
    jbtPrevious.setText("<");
    jbtNext.setText(">");
    //Panel to hold details about the person
    JPanel jpDetails = new JPanel();
    jpDetails.setBorder(new TitledBorder("Details"));
    jpDetails.setLayout(new GridLayout(4, 2));
    jpDetails.add(new JLabel("Name"));
    jpDetails.add(jtfName = new JTextField());
    jpDetails.add(new JLabel("DOB"));
    jpDetails.add(jtfDOB = new JTextField());
    jpDetails.add(new JLabel("National insurance number"));
    jpDetails.add(jtfNI = new JTextField());
    jpDetails.add(new JLabel("StaffID"));
    jpDetails.add(jtfStaffID = new JTextField());
    try
    jtfName.setText(peopleInfo.people[currentRecord].personsName);
    /* jtfDOB.setText(String.valueOf(
    peopleInfo.people[currentRecord].personsDOB));
    jtfNI.setText(String.valueOf(
    peopleInfo.people[currentRecord].personsNI));
    jtfStaffID.setText(String.valueOf(
    peopleInfo.people[currentRecord].personsStaffID));*/
    catch (Exception e)
    System.out.print(e);
    imagePanel.setBorder(new TitledBorder("Face"));
    imagePanel.add(jbtLoadFace = new JButton("Load Face"));
    //Main body panel
    JPanel jpBody = new JPanel();
    jpBody.add(imagePanel, BorderLayout.WEST);
    jpBody.add(jpDetails, BorderLayout.CENTER);
    //Place panels on frame
    getContentPane().setLayout(new BorderLayout());
    getContentPane().add(jpBody, BorderLayout.CENTER);
    getContentPane().add(jpButtons, BorderLayout.SOUTH);
    //Register listeners
    jbtLoadFace.addActionListener(this);
    jbtPrevious.addActionListener(this);
    jbtNext.addActionListener(this);
    //jtfName.addKeyListener(this);
    jtfDOB.addKeyListener(this);
    jtfNI.addKeyListener(this);
    jtfStaffID.addKeyListener(this);
    public void actionPerformed(ActionEvent e)
    boolean goOn = false;
    if (e.getSource() == jbtLoadFace)
    isRecordModified = true;
    setTitle("Set up datbase: Record Modified");
    if (e.getSource() == jbtPrevious || e.getSource() == jbtNext)
    if (isRecordModified == true)
    int result = JOptionPane.showConfirmDialog(
    null,
    "Do you want to save changes to this record?",
    "Face datbase",
    JOptionPane.YES_NO_CANCEL_OPTION);
    switch (result)
    case JOptionPane.YES_OPTION:
    saveRecordChanges();
    goOn = true;
    break;
    case JOptionPane.NO_OPTION:
    goOn = true;
    break;
    if (goOn == true)
    //If user has not cancelled move to another record
    if (e.getSource() == jbtPrevious)
    moveForwardToRecord(true);
    else
    moveForwardToRecord(false);
    public void saveRecordChanges()
    boolean alreadyInDatabase = false;
    //Put the values in the field into the database
    try
    if (currentRecord < peopleInfo.people.length)
    alreadyInDatabase = true;
    peopleInfo.people[currentRecord].personsName =
    jtfName.getText();
    peopleInfo.people[currentRecord].personsDOB =
    Integer.parseInt(jtfDOB.getText());
    peopleInfo.people[currentRecord].personsNI =
    Integer.parseInt(jtfNI.getText());
    peopleInfo.people[currentRecord].personsStaffID =
    Integer.parseInt(jtfStaffID.getText());
    catch (Exception e)
    System.out.print(e);
    if (alreadyInDatabase = false)
    newPeople.add(new person("", jtfName.getText(),
    Integer.parseInt(jtfDOB.getText()),
    Integer.parseInt(jtfNI.getText()),
    Integer.parseInt(jtfStaffID.getText())));
    public void moveForwardToRecord(boolean forward)
    isRecordModified = false;
    setTitle("Set up datbase");
    if (forward)
    else
    public void keyPressed(KeyEvent e)
    isRecordModified = true;
    setTitle("Set up datbase: Record Modified");
    public void keyReleased(KeyEvent e) {
    public void keyTyped(KeyEvent e) {
    //Open a file
    private void open()
    if (jFileChooser.showOpenDialog(this) == JFileChooser.APPROVE_OPTION)
    String fileName = jFileChooser.getSelectedFile().getPath();
    imagePanel.setImageIcon(new ImageIcon(fileName));
    isRecordModified = true;
    setTitle("Set up datbase: Record Modified");
    //--- cFaceRecData.java ---
    //--- Edmund Smith 18/11/04 ---
    //--- Stores and retrives info about a person and their face ---
    import java.io.*;
    import java.util.*;
    class cFaceRecData
    //The location of the database
    final String dbPath = "C:/Documents and Settings/" +
    "Edmund Smith/My Documents/fdatabase.dat";
    //The data
    allPeople inPeople;
    //Saves the file
    void saveDatabase(allPeople outPeople)
    try
    //Object output stream
    ObjectOutputStream out =
    new ObjectOutputStream(new FileOutputStream(dbPath));
    //Write the object
    out.writeObject(outPeople);
    //Close the object output stream
    out.close();
    catch (IOException ex)
    System.out.println(ex);
    //Opens the file
    allPeople restoreDatabase()
    try
    //Object input steam
    ObjectInputStream in =
    new ObjectInputStream(new FileInputStream(dbPath));
    //Get the database
    inPeople = (allPeople)in.readObject();
    //Close the input stream
    in.close();
    catch (IOException ex)
    System.out.println(ex);
    catch (ClassNotFoundException ex)
    System.out.println(ex);
    //Return the database
    return inPeople;
    //Holds the info about a person
    class person
    //Stores the location of the image on disk
    String path;
    //Stores the name of a person
    String personsName;
    //Stores the dob of a person, their NI no, and employee ID
    int personsDOB, personsNI, personsStaffID;
    //Default constructor
    public person(String inPath, String inName, int inDOB, int inNI,
    int inStaffID)
    //Stores the values which passed in
    path = inPath;
    personsName = inName;
    personsDOB = inDOB;
    personsNI = inNI;
    personsStaffID = inStaffID;
    //The database
    class allPeople
    person[] people;
    int numPeople;
    //Default constructor
    public allPeople(person[] persons)
    //Create the array to hold the people
    people = new person[persons.length];
    for (int i = 0; i < persons.length; i++)
    people = new person(persons.path,
    persons.personsName,
    persons.personsDOB,
    persons.personsStaffID,
    persons.personsNI);
    //Updates the database
    public allPeople(allPeople thePeople, person[] persons)
    //Create the array to hold the people
    int totalPeople = thePeople.people.length + persons.length;
    people = new person[totalPeople];
    for (int i = 0; i < totalPeople; i++)
    if (i < thePeople.people.length)
    people = new person(thePeople.people.path,
    thePeople.people.personsName,
    thePeople.people.personsDOB,
    thePeople.people.personsStaffID,
    thePeople.people.personsNI);
    else
    people = new person(persons.path,
    persons.personsName,
    persons.personsDOB,
    persons.personsStaffID,
    persons.personsNI);
    }

    line 80 is jtfName.setText(peopleInfo.people[currentRecord].personsName);So put these lines between line 79 and 80System.out.println(jtfName);System.out.println(peopleInfo);
    System.out.println(peopleInfo.people);
    System.out.println(peopleInfo.people[currentRecord]);
    System.out.println(peopleInfo.people[currentRecord].personsName);One of those will print null. Then you will see a NullPointerException. Then you can trace your code back to where you are setting these to some value.

  • Not able to load objects

    I have written code to load in an object but this keeps giving me exceptions when i run the code to try and display the data from the object read in. My code is below:
    Thanks
    //--- cFaceRecGUIMain.java ---
    //--- Edmund Smith 23/08/04 ---
    //--- The GUI for the face recognition sofware contains buttons and ---
    //--- display area for an image of a face ---
    import java.awt.*;
    import java.awt.image.*;
    import java.awt.event.*;
    import java.io.*;
    import javax.swing.*;
    import javax.swing.border.*;
    public class cFaceRecGUIMain extends JFrame implements ActionListener {
    //Create menu bar items
    private JMenuItem jmiLoadPicture, jmiExit, jmiEdit;
    //Recognize Button
    private JButton jbtRecognize;
    //Labels with info about picture
    private String lblName, lblDOB, lblNI, lblStaffID;
    //Panel to hold an image
    private ImagePanel imagePanel = new ImagePanel();
    //File Chooser
    JFileChooser jFileChooser = new JFileChooser();
    //BitmapReader
    //cGetBytes getBytes = new cGetBytes();
    //Face database
    cFaceRecData faceDatabase = new cFaceRecData();
    //Set default window sizes
    final int xSize = 600;
    final int ySize = 400;
    //Array for holding pixels
    int pixels[];
    //Labels for menu items
    final String lbljmiLoadPicture = "Load Picture for recogniton";
    final String lbljmiExit = "Exit";
    final String lbljmiEdit = "Edit face database";
    //Create the frame to enter details about people
    cFaceRecGUIEDetails enterDetailsFrame = new cFaceRecGUIEDetails();
    //BitmapReader
    cGetBytes getImageBytes = new cGetBytes();
    //Main method
    public static void main(String[] args)
    cFaceRecGUIMain programFrame = new cFaceRecGUIMain();
    programFrame.pack();
    programFrame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    programFrame.setTitle("Face Recognizer");
    programFrame.setSize(600, 400);
    programFrame.setVisible(true);
    //Constructor
    public cFaceRecGUIMain() {
    //Initialize menu bar
    JMenuBar jmb = new JMenuBar();
    setJMenuBar(jmb);
    //Add menus
    JMenu fileMenu = new JMenu("File");
    fileMenu.setMnemonic('F');
    jmb.add(fileMenu);
    JMenu faceMenu = new JMenu("Face");
    fileMenu.setMnemonic('A');
    jmb.add(faceMenu);
    JMenu helpMenu = new JMenu("Help");
    fileMenu.setMnemonic('H');
    jmb.add(helpMenu);
    //Add menu items
    fileMenu.add(jmiLoadPicture =
    new JMenuItem(lbljmiLoadPicture, 'L'));
    fileMenu.addSeparator();
    fileMenu.add(jmiExit = new JMenuItem(lbljmiExit, 'X'));
    faceMenu.add(jmiEdit = new JMenuItem(lbljmiEdit, 'E'));
    //Set keyboard accelerators
    jmiExit.setAccelerator(
    KeyStroke.getKeyStroke(KeyEvent.VK_E, ActionEvent.CTRL_MASK));
    jmiLoadPicture.setAccelerator(
    KeyStroke.getKeyStroke(KeyEvent.VK_L, ActionEvent.CTRL_MASK));
    //Set up new panel
    imagePanel.setBorder(new TitledBorder("Face"));
    //Lay components on panel
    imagePanel.setImageIcon(new ImageIcon("C:/Documents and Settings/" +
    "Edmund Smith/My Documents/aface.bmp"));
    imagePanel.add(jbtRecognize = new JButton("Recognize"),
    BorderLayout.SOUTH);
    setTitle("Face Recognizer");
    //Labels to hold info
    JPanel lblsAboutImagePanel = new JPanel();
    lblsAboutImagePanel.setBorder(new TitledBorder("Details"));
    lblsAboutImagePanel.setLayout(new GridLayout(4, 2));
    lblsAboutImagePanel.add(new JLabel("Name"));
    lblsAboutImagePanel.add(new JLabel(lblName));
    lblsAboutImagePanel.add(new JLabel("DOB"));
    lblsAboutImagePanel.add(new JLabel(lblDOB));
    lblsAboutImagePanel.add(new JLabel("National insurance number"));
    lblsAboutImagePanel.add(new JLabel(lblNI));
    lblsAboutImagePanel.add(new JLabel("Staff ID"));
    lblsAboutImagePanel.add(new JLabel(lblStaffID));
    //Add the different panels to the frame
    getContentPane().setLayout(new BorderLayout());
    getContentPane().add(imagePanel, BorderLayout.WEST);
    getContentPane().add(lblsAboutImagePanel, BorderLayout.CENTER);
    //Register listeners
    jmiExit.addActionListener(this);
    jmiLoadPicture.addActionListener(this);
    jmiEdit.addActionListener(this);
    //Create the frame where you can enter the details of a person
    enterDetailsFrame.pack();
    enterDetailsFrame.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
    enterDetailsFrame.setTitle("Set up database");
    enterDetailsFrame.setSize(xSize, ySize);
    class edfClosingListener extends WindowAdapter {
    public void windowClosing(WindowEvent e) {
    //Check to see if the record has been changed
    if (enterDetailsFrame.isRecordModified)
    JOptionPane.showConfirmDialog(
    null,
    "Do you want to save changes to this record?",
    "Face datbase",
    JOptionPane.YES_NO_CANCEL_OPTION);
    if (enterDetailsFrame.newPeople.size() > 0)
    //create a temporary array to store the new people
    person[] newPersons = new
    person[enterDetailsFrame.newPeople.size()];
    //Copy the people in the vector to the array
    person tempPerson;
              for (int i = 0; i < newPersons.length; i++)
    tempPerson =
    (person)enterDetailsFrame.newPeople.elementAt(i);
    newPersons.path = tempPerson.path;
    newPersons[i].personsName = tempPerson.personsName;
    newPersons[i].personsDOB = tempPerson.personsDOB;
    newPersons[i].personsNI = tempPerson.personsNI;
    newPersons[i].personsStaffID = tempPerson.personsStaffID;
    //Create new database
    allPeople outPeople =
    new allPeople(enterDetailsFrame.peopleInfo, newPersons);
    //Save the database with the added records
    enterDetailsFrame.faceDatabase.saveDatabase(outPeople);
    else
    //Save the database with the same number of records
    enterDetailsFrame.faceDatabase.saveDatabase(
    enterDetailsFrame.peopleInfo);
    //Set the actions to happen when windows are closed
    enterDetailsFrame.addWindowListener(new edfClosingListener());
    closeWindow closeMainFrame = new closeWindow();
    addWindowListener(closeMainFrame);
    public void actionPerformed(ActionEvent e)
    String actionCommand = e.getActionCommand();
    if (e.getSource() instanceof JMenuItem) {
    if (lbljmiExit.equals(actionCommand))
    System.exit(0);
    else if (lbljmiLoadPicture.equals(actionCommand))
    open();
    else if (lbljmiEdit.equals(actionCommand)) {
    enterDetailsFrame.setVisible(true);
    //No records have been modified
    enterDetailsFrame.isRecordModified = false;
    //Open a file
    private void open() {
    if (jFileChooser.showOpenDialog(this) == JFileChooser.APPROVE_OPTION)
    try {
    //Get the file name
    String fileName = jFileChooser.getSelectedFile().getPath();
    //Display the image
    ImageIcon imagei = new ImageIcon(fileName);
    imagePanel.setImageIcon(imagei);
    //Set size of array for holiding bytes in the image
    pixels =
    new int[51 * 55];
    //Get the pixels
    // getBytes.getBMPImage(new FileInputStream(new File(fileName)), pixels);
    catch (Exception e) {
    System.out.print(e);
    class ImagePanel extends JPanel {
    //Label to hold the face
    private JLabel jlblFace = new JLabel();
    //Constructor
    public ImagePanel() {
    setLayout(new BorderLayout());
    add(jlblFace, BorderLayout.CENTER);
    //Set image and show it
    public void setImageIcon(ImageIcon icon) {
    jlblFace.setIcon(icon);
    Dimension dimension =
    new Dimension(icon.getIconWidth(), icon.getIconHeight());
    jlblFace.setPreferredSize(dimension);
    //--- cFaceRecGUIEDetails.java ---
    //--- Edmund Smith 06/10/04 ---
    //--- Allows the user to enter details about a person, view the ---
    //--- database and add people to the database ---
    import javax.swing.*;
    import java.awt.*;
    import java.awt.event.*;
    import javax.swing.border.*;
    import java.util.*;
    class cFaceRecGUIEDetails extends JFrame implements KeyListener, ActionListener
    //Buttons to navigate the database
    private JButton jbtPrevious, jbtNext;
    //Button to load a face
    private JButton jbtLoadFace;
    //Fields to display info about the person
    private JTextField jtfName, jtfDOB, jtfNI, jtfStaffID;
    //Panel to hold an image
    private ImagePanel imagePanel = new ImagePanel();
    //File Chooser
    private JFileChooser jFileChooser = new JFileChooser();
    //Variable to tell whether record has been modified
    boolean isRecordModified = false;
    //Tells which record current being veiwed/changed
    int currentRecord = 0;
    //Stores new people to be added to database
    Vector newPeople = new Vector();
    //Face database
    cFaceRecData faceDatabase;
    public allPeople peopleInfo;
    //Default Constructor
    public cFaceRecGUIEDetails()
    //Get the face database
    faceDatabase = new cFaceRecData();
    peopleInfo = faceDatabase.restoreDatabase();
    //Panel to hold two buttons to navigate the database
    JPanel jpButtons = new JPanel();
    //Add navigation buttons to panel
    jpButtons.setLayout(new FlowLayout());
    jpButtons.add(jbtPrevious = new JButton());
    jpButtons.add(jbtNext = new JButton());
    //Set button text
    jbtPrevious.setText("<");
    jbtNext.setText(">");
    //Panel to hold details about the person
    JPanel jpDetails = new JPanel();
    jpDetails.setBorder(new TitledBorder("Details"));
    jpDetails.setLayout(new GridLayout(4, 2));
    jpDetails.add(new JLabel("Name"));
    jpDetails.add(jtfName = new JTextField());
    jpDetails.add(new JLabel("DOB"));
    jpDetails.add(jtfDOB = new JTextField());
    jpDetails.add(new JLabel("National insurance number"));
    jpDetails.add(jtfNI = new JTextField());
    jpDetails.add(new JLabel("StaffID"));
    jpDetails.add(jtfStaffID = new JTextField());
    try
    jtfName.setText(peopleInfo.people[currentRecord].personsName);
    /* jtfDOB.setText(String.valueOf(
    peopleInfo.people[currentRecord].personsDOB));
    jtfNI.setText(String.valueOf(
    peopleInfo.people[currentRecord].personsNI));
    jtfStaffID.setText(String.valueOf(
    peopleInfo.people[currentRecord].personsStaffID));*/
    catch (Exception e)
    System.out.print(e);
    imagePanel.setBorder(new TitledBorder("Face"));
    imagePanel.add(jbtLoadFace = new JButton("Load Face"));
    //Main body panel
    JPanel jpBody = new JPanel();
    jpBody.add(imagePanel, BorderLayout.WEST);
    jpBody.add(jpDetails, BorderLayout.CENTER);
    //Place panels on frame
    getContentPane().setLayout(new BorderLayout());
    getContentPane().add(jpBody, BorderLayout.CENTER);
    getContentPane().add(jpButtons, BorderLayout.SOUTH);
    //Register listeners
    jbtLoadFace.addActionListener(this);
    jbtPrevious.addActionListener(this);
    jbtNext.addActionListener(this);
    //jtfName.addKeyListener(this);
    jtfDOB.addKeyListener(this);
    jtfNI.addKeyListener(this);
    jtfStaffID.addKeyListener(this);
    public void actionPerformed(ActionEvent e)
    boolean goOn = false;
    if (e.getSource() == jbtLoadFace)
    isRecordModified = true;
    setTitle("Set up datbase: Record Modified");
    if (e.getSource() == jbtPrevious || e.getSource() == jbtNext)
    if (isRecordModified == true)
    int result = JOptionPane.showConfirmDialog(
    null,
    "Do you want to save changes to this record?",
    "Face datbase",
    JOptionPane.YES_NO_CANCEL_OPTION);
    switch (result)
    case JOptionPane.YES_OPTION:
    saveRecordChanges();
    goOn = true;
    break;
    case JOptionPane.NO_OPTION:
    goOn = true;
    break;
    if (goOn == true)
    //If user has not cancelled move to another record
    if (e.getSource() == jbtPrevious)
    moveForwardToRecord(true);
    else
    moveForwardToRecord(false);
    public void saveRecordChanges()
    boolean alreadyInDatabase = false;
    //Put the values in the field into the database
    try
    if (currentRecord < peopleInfo.people.length)
    alreadyInDatabase = true;
    peopleInfo.people[currentRecord].personsName =
    jtfName.getText();
    peopleInfo.people[currentRecord].personsDOB =
    Integer.parseInt(jtfDOB.getText());
    peopleInfo.people[currentRecord].personsNI =
    Integer.parseInt(jtfNI.getText());
    peopleInfo.people[currentRecord].personsStaffID =
    Integer.parseInt(jtfStaffID.getText());
    catch (Exception e)
    System.out.print(e);
    if (alreadyInDatabase = false)
    newPeople.add(new person("", jtfName.getText(),
    Integer.parseInt(jtfDOB.getText()),
    Integer.parseInt(jtfNI.getText()),
    Integer.parseInt(jtfStaffID.getText())));
    public void moveForwardToRecord(boolean forward)
    isRecordModified = false;
    setTitle("Set up datbase");
    if (forward)
    else
    public void keyPressed(KeyEvent e)
    isRecordModified = true;
    setTitle("Set up datbase: Record Modified");
    public void keyReleased(KeyEvent e) {
    public void keyTyped(KeyEvent e) {
    //Open a file
    private void open()
    if (jFileChooser.showOpenDialog(this) == JFileChooser.APPROVE_OPTION)
    String fileName = jFileChooser.getSelectedFile().getPath();
    imagePanel.setImageIcon(new ImageIcon(fileName));
    isRecordModified = true;
    setTitle("Set up datbase: Record Modified");
    //--- cFaceRecData.java ---
    //--- Edmund Smith 18/11/04 ---
    //--- Stores and retrives info about a person and their face ---
    import java.io.*;
    import java.util.*;
    class cFaceRecData
    //The location of the database
    final String dbPath = "C:/Documents and Settings/" +
    "Edmund Smith/My Documents/fdatabase.dat";
    //The data
    allPeople inPeople;
    //Saves the file
    void saveDatabase(allPeople outPeople)
    try
    //Object output stream
    ObjectOutputStream out =
    new ObjectOutputStream(new FileOutputStream(dbPath));
    //Write the object
    out.writeObject(outPeople);
    //Close the object output stream
    out.close();
    catch (IOException ex)
    System.out.println(ex);
    //Opens the file
    allPeople restoreDatabase()
    try
    //Object input steam
    ObjectInputStream in =
    new ObjectInputStream(new FileInputStream(dbPath));
    //Get the database
    inPeople = (allPeople)in.readObject();
    //Close the input stream
    in.close();
    catch (IOException ex)
    System.out.println(ex);
    catch (ClassNotFoundException ex)
    System.out.println(ex);
    //Return the database
    return inPeople;
    //Holds the info about a person
    class person
    //Stores the location of the image on disk
    String path;
    //Stores the name of a person
    String personsName;
    //Stores the dob of a person, their NI no, and employee ID
    int personsDOB, personsNI, personsStaffID;
    //Default constructor
    public person(String inPath, String inName, int inDOB, int inNI,
    int inStaffID)
    //Stores the values which passed in
    path = inPath;
    personsName = inName;
    personsDOB = inDOB;
    personsNI = inNI;
    personsStaffID = inStaffID;
    //The database
    class allPeople
    person[] people;
    int numPeople;
    //Default constructor
    public allPeople(person[] persons)
    //Create the array to hold the people
    people = new person[persons.length];
    for (int i = 0; i < persons.length; i++)
    people[i] = new person(persons[i].path,
    persons[i].personsName,
    persons[i].personsDOB,
    persons[i].personsStaffID,
    persons[i].personsNI);
    //Updates the database
    public allPeople(allPeople thePeople, person[] persons)
    //Create the array to hold the people
    int totalPeople = thePeople.people.length + persons.length;
    people = new person[totalPeople];
    for (int i = 0; i < totalPeople; i++)
    if (i < thePeople.people.length)
    people[i] = new person(thePeople.people[i].path,
    thePeople.people[i].personsName,
    thePeople.people[i].personsDOB,
    thePeople.people[i].personsStaffID,
    thePeople.people[i].personsNI);
    else
    people[i] = new person(persons[i].path,
    persons[i].personsName,
    persons[i].personsDOB,
    persons[i].personsStaffID,
    persons[i].personsNI);

    When posting code to the forum, please use the code button.
    Also, post the exception message and indicate the line that gives the error.

  • How can i plot a histogram with using the results of Line Length

    PLS HELP.How can i prepare a histogram with using the results of line length code(It is somewhere in the middle).
    This is a final exam take-home question. I would appreciate if you can help?
    import java.awt.*;
    import java.awt.event.*;
    import java.io.*;
    import javax.swing.*;
    import java.text.*;
    import java.io.File;
    public class WordAnalyser extends JFrame implements ActionListener
    private JMenuItem jmiAc, jmiSil, jmiCikis, jmiAnaliz, jmiHakkinda, jmiKullanim;
    private JTextArea jta1, jta2;
    private JFileChooser jFileChooser = new JFileChooser();
    File hafizada;
    File aktarilan = new File("Sonuc.txt");
    // Main method
    public static void main(String[] args)
    WordAnalyser frame = new WordAnalyser(); /* Ana ekran olusturulur */
    frame.setSize(400, 300); /* Degerleri belirlenir */
    frame.setVisible(true); /* Gorunebilirligi ayarlanir */
    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    public WordAnalyser()
    setTitle("Serkan Ozgen Dosya Inceleme Programina Hos Geldiniz");
    JMenuBar mb = new JMenuBar();
    setJMenuBar(mb);
    JMenu fileMenu = new JMenu("Dosya");
    fileMenu.setMnemonic('F');
    mb.add(fileMenu);
    JMenu helpMenu = new JMenu("Degerlendirme");
    helpMenu.setMnemonic('H');
    mb.add(helpMenu);
    JMenu kullanimMenu = new JMenu("Kullanim Kilavuzu");
    mb.add(kullanimMenu);     
    fileMenu.add(jmiAc = new JMenuItem("Ac", 'A'));
    fileMenu.add(jmiSil = new JMenuItem("Sil", 'S'));
    fileMenu.add(jmiCikis = new JMenuItem("Cikis", 'C'));
    helpMenu.add(jmiAnaliz = new JMenuItem("Analiz", 'D'));
    helpMenu.add(jmiHakkinda = new JMenuItem("Hakkinda", 'H'));
    kullanimMenu.add(jmiKullanim = new JMenuItem("Kullanim"));     
    getContentPane().add(new JScrollPane(jta1 = new JTextArea()), BorderLayout.CENTER);
    getContentPane().add(jta2 = new JTextArea(), BorderLayout.SOUTH);
    jmiAc.addActionListener(this);
    jmiSil.addActionListener(this);
    jmiCikis.addActionListener(this);
    jmiAnaliz.addActionListener(this);
    jmiHakkinda.addActionListener(this);
    jmiKullanim.addActionListener(this);
    public void actionPerformed(ActionEvent e)
    String actionCommand = e.getActionCommand();
    if (e.getSource() instanceof JMenuItem)
    if ("Ac".equals(actionCommand))
    Ac();
    else if ("Sil".equals(actionCommand))
    Sil();
    else if ("Cikis".equals(actionCommand))
    System.exit(0);
    else if ("Analiz".equals(actionCommand))
    sayim();
    else if ("Hakkinda".equals(actionCommand))
    JOptionPane.showMessageDialog(this,
    "!!!! Bu program text analizi gerceklestirir. Her hakki saklidir SERKAN OZGEN!!!!",
    "Bu program hakkinda",
    JOptionPane.INFORMATION_MESSAGE);
    else if ("Kullanim".equals(actionCommand))
         JOptionPane.showMessageDialog(this,
         " Ilk once dosya menusunden Ac i tiklayarak analiz etmek istediginiz Dosyayi seciniz (Lutfen uzantisi *.txt \nveya *.log olsun). Daha sonra Degerlendirme menusunden analizi tiklarsaniz dosyanizda kac adet rakam, harf, \ncumle ve kelime oldugunu gorebilirsiniz. Simdiden kolay gelsin",
         "Programin kullanim detaylari",
         JOptionPane.INFORMATION_MESSAGE);
    private void Ac()
    if (jFileChooser.showOpenDialog(this) == JFileChooser.APPROVE_OPTION)
    hafizada = jFileChooser.getSelectedFile();
    Ac(hafizada);
    // Acilan Dosyayi ana ekranda gostermeye yariyan bir method
    private void Ac(File file)
    try
    // Acilan dosyayi okuma ve ana ekranda gosterme
    BufferedInputStream in = new BufferedInputStream(new FileInputStream(file));
    byte[] b = new byte[in.available()];
    in.read(b, 0, b.length);
    jta1.append(new String(b, 0, b.length));
    in.close();
    catch (IOException ex)
    // Temizle tusunun hangi ekranlara etki edecegini secme
    private void Sil()
    jta1.setText("");
    jta2.setText("");
    private void sayim()
    int buff;
    int sayac = 0;
    int Cumleler = 0;
    int Kelimeler = 0;
    int Karakterler = 0;
    int Satirlar = 0;
    int Rakamlar = 0;     
    boolean start = true;
    int linenum = 0;     
    try
    FileInputStream instream = new FileInputStream(hafizada);
    FileOutputStream outstream = new FileOutputStream(aktarilan);
         BufferedReader infile = new BufferedReader(new InputStreamReader(new FileInputStream(hafizada)));
    PrintStream out = new PrintStream(outstream);
         out.println("---Kelime Avcisinin Sonuclari---");
         String line = infile.readLine();
         while (line != null){
         int len = line.length();
         linenum++;
         line = infile.readLine();
         out.println("Line Length :"     + linenum + "\t" +len);
    while ((buff=instream.read()) != -1)
    switch((char)buff)
    case '?': case '.': case '!': /* Eger "?", "." veya "!" gorurse program cumleleri ve kelimeleri arttirir*/
    if (start == false)
    Cumleler++;
    Kelimeler++;
    start = true;
    break;
    case ' ': case '\t': case ',': case ';': case ':': case'\"': case'\'': /* Eger /t,;:\ ve \" bu isarteleri goruruse program kelimeleri arttirir */
    if (start == false)
    Kelimeler++;
    start = true;
    break;
              case 'n': case '\n': /* Eger \n gorurse satirlari arttirir */
              if (start == false)
                   Satirlar++;
                   Kelimeler++;
                   start = true;
              break;
    default:
    if (((char)buff >= 'a' && (char)buff<='z')|| /*a-z, A-Z veya - degerlerini gorurse karakterler arttirilir */
    ((char)buff >= 'A' && (char)buff<='Z')||
    ((char)buff == '-'))
    Karakterler++;
    if ((Kelimeler % 50) == 49)
    if (start == true)
                   out.println();     
    out.print((Kelimeler+1) + " ");
    out.print((char)buff);
    start = false;
              if ((char)buff >='0' && (char)buff <='9') {  /* 0-9 gorurse rakamlari arttiri */
                   Rakamlar++; }
    }// switch
         }//while
    instream.close();
    out.println();
    out.println();
    out.println("Karakter sayisi: " + Karakterler);
         out.println("Kelime sayisi: " + Kelimeler);
    out.println("Cumle sayisi: " + Cumleler);
         out.println("Satir sayisi: "+ Satirlar);
         out.println("Rakam sayisi: "+ Rakamlar);
    outstream.close();
    try
    BufferedInputStream in = new BufferedInputStream(new FileInputStream(aktarilan));
    byte[] b = new byte[in.available()];
    in.read(b, 0, b.length);
    jta2.append(new String(b, 0, b.length));
    in.close();
    catch (IOException ex)
    catch (Exception e)
    System.out.println(e);
    }

    Why is it that you're not interested in IOExceptions?
    catch (IOException ex)
    } Empty catch blocks is a hallmark of foolish Java code. At least print out the stack trace.
    %

  • How can i add the first to the following

    String line = infile.readLine();
    int linenum = 0;
    while (line != null) {
    int len = line.length();
    linenum++;
    System.out.println(linenum + "\t" + len);
    line = infile.readLine();
    import java.awt.*;
    import java.awt.event.*;
    import java.io.*;
    import javax.swing.*;
    import java.text.*;
    public class WordAnalyser extends JFrame implements ActionListener
    // Menu items Open, Clear, Exit, WordCount, About
    private JMenuItem jmiOpen, jmiClear, jmiExit, jmiWordCount, jmiAbout;
    // Text area for displaying and editing text files
    private JTextArea jta1, jta2;
    // Status label for displaying operation status
    private JLabel jlblStatus;
    // File dialog box
    private JFileChooser jFileChooser = new JFileChooser();
    File infile;
    File outfile = new File("OutFile.txt");
    DecimalFormat numForm1 = new DecimalFormat("000");
    DecimalFormat numForm2 = new DecimalFormat("0.00");
    // Main method
    public static void main(String[] args)
    WordAnalyser frame = new WordAnalyser();
    frame.setSize(500, 400);
    frame.center();
    frame.setVisible(true);
    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    public WordAnalyser()
    setTitle("Word Analyser");
    // Create a menu bar mb and attach to the frame
    JMenuBar mb = new JMenuBar();
    setJMenuBar(mb);
    // Add a "File" menu in mb
    JMenu fileMenu = new JMenu("File");
    fileMenu.setMnemonic('F');
    mb.add(fileMenu);
    // Add a "Help" menu in mb
    JMenu helpMenu = new JMenu("Help");
    helpMenu.setMnemonic('H');
    mb.add(helpMenu);
    // Create and add menu items to the menu
    fileMenu.add(jmiOpen = new JMenuItem("Open", 'O'));
    fileMenu.add(jmiClear = new JMenuItem("Clear", 'C'));
    fileMenu.addSeparator();
    fileMenu.add(jmiExit = new JMenuItem("Exit", 'E'));
    helpMenu.add(jmiWordCount = new JMenuItem("Word Count", 'W'));
    helpMenu.add(jmiAbout = new JMenuItem("About", 'A'));
    // Set default directory to the current directory
    jFileChooser.setCurrentDirectory(new File("."));
    // Set BorderLayout for the frame
    getContentPane().add(new JScrollPane(jta1 = new JTextArea()), BorderLayout.CENTER);
    getContentPane().add(jta2 = new JTextArea(), BorderLayout.EAST);
    getContentPane().add(jlblStatus = new JLabel(), BorderLayout.SOUTH);
    // Register listeners
    jmiOpen.addActionListener(this);
    jmiClear.addActionListener(this);
    jmiExit.addActionListener(this);
    jmiWordCount.addActionListener(this);
    jmiAbout.addActionListener(this);
    public void center()
    // Get the screen dimension
    Dimension screenSize = Toolkit.getDefaultToolkit().getScreenSize();
    int screenWidth = screenSize.width;
    int screenHeight = screenSize.height;
    // Get the frame dimension
    Dimension frameSize = this.getSize();
    int x = (screenWidth - frameSize.width)/2;
    int y = (screenHeight - frameSize.height)/2;
    // Determine the location of the left corner of the frame
    if (x < 0)
    x = 0;
    frameSize.width = screenWidth;
    if (y < 0)
    y = 0;
    frameSize.height = screenHeight;
    // Set the frame to the specified location
    this.setLocation(x, y);
    // Handle ActionEvent for menu items
    public void actionPerformed(ActionEvent e)
    String actionCommand = e.getActionCommand();
    if (e.getSource() instanceof JMenuItem)
    if ("Open".equals(actionCommand))
    open();
    else if ("Clear".equals(actionCommand))
    clear();
    else if ("Exit".equals(actionCommand))
    System.exit(0);
    else if ("Word Count".equals(actionCommand))
    word_count();
    else if ("About".equals(actionCommand))
    JOptionPane.showMessageDialog(this,
    "Program performs text analysis",
    "About This Program",
    JOptionPane.INFORMATION_MESSAGE);
    // Open file
    private void open()
    if (jFileChooser.showOpenDialog(this) == JFileChooser.APPROVE_OPTION)
    infile = jFileChooser.getSelectedFile();
    open(infile);
    // Open file with the specified File instance
    private void open(File file)
    try
    // Read from the specified file and store it in jta
    BufferedInputStream in = new BufferedInputStream(new FileInputStream(file));
    byte[] b = new byte[in.available()];
    in.read(b, 0, b.length);
    jta1.append(new String(b, 0, b.length));
    in.close();
    // Display the status of the Open file operation in jlblStatus
    jlblStatus.setText(file.getName() + " Opened");
    catch (IOException ex)
    jlblStatus.setText("Error opening " + file.getName());
    // Clear all display areas
    private void clear()
    jta1.setText("");
    jta2.setText("");
    jlblStatus.setText("");
    // Perform word analysis with specified File instance
    private void word_count()
    int buff; // for reading 1 char at a time
    int count = 0;
    int sentences = 0;
    int words = 0;
    int chars = 0;
    boolean start = true;
    try
    FileInputStream instream = new FileInputStream(infile);
    FileOutputStream outstream = new FileOutputStream(outfile);
    // convert FileOutputSream object to PrintStream object for easier output
    PrintStream out = new PrintStream(outstream);
    out.println("---Word Analysis---");
    while ((buff=instream.read()) != -1)
    switch((char)buff)
    case '?': case '.': case '!':
    if (start == false)
    sentences++;
    words++;
    start = true;
    break;
    case ' ': case '\t': case '\n': case ',': case ';': case ':': case'\"': case'\'':
    if (start == false)
    words++;
    start = true;
    break;
    default:
    // 3-digit integer format
    if (((char)buff >= 'a' && (char)buff<='z')||
    ((char)buff >= 'A' && (char)buff<='Z')||
    ((char)buff >= '0' && (char)buff <= '9')||
    ((char)buff == '-'))
    chars++;
    if ((words % 50) == 49)
    if (start == true)
    out.println();
    out.print(numForm1.format(words+1) + " ");
    out.print((char)buff);
    start = false;
    }// switch
    }//while
    instream.close();
    out.println();
    out.println();
    out.println("Number of characters: " + chars);
    out.println("Number of words: " + words);
    out.println("Number of sentences: " + sentences);
    out.print("Number of words per sentence: ");
    // cast integers to float, then add 0.005 to round up to 2 decimal places
    out.println(numForm2.format((float)words/sentences));
    outstream.close();
    try
    //Read from the output file and display in jta
    BufferedInputStream in = new BufferedInputStream(new FileInputStream(outfile));
    byte[] b = new byte[in.available()];
    in.read(b, 0, b.length);
    jta2.append(new String(b, 0, b.length));
    in.close();
    catch (IOException ex)
    jlblStatus.setText("Error opening " + outfile.getName());
    catch (Exception e)
    System.out.println(e);
    }

    Do you want to add the code
    String line = infile.readLine();
    int linenum = 0;
    while (line != null) {
    int len = line.length();
    linenum++;
    System.out.println(linenum + "\t" + len);
    line = infile.readLine();
    }to your rest of the program?

  • Plz help me out with class loader problem

    hai forum members,
    I have a code which loads class files from local disk.
    It works fine with some classes ,
    But i get this exception when i am selecting certain other class files
    I am using jdeveloper.
    Exception in thread "AWT-EventQueue-0" java.lang.NoClassDefFoundError: Filter (wrong name: project1/Filter)
         at java.lang.ClassLoader.defineClass1(Native Method)
         at java.lang.ClassLoader.defineClass(ClassLoader.java:620)
         at java.security.SecureClassLoader.defineClass(SecureClassLoader.java:124)
         at java.net.URLClassLoader.defineClass(URLClassLoader.java:260)
         at java.net.URLClassLoader.access$100(URLClassLoader.java:56)
         at java.net.URLClassLoader$1.run(URLClassLoader.java:195)
         at java.security.AccessController.doPrivileged(Native Method)
         at java.net.URLClassLoader.findClass(URLClassLoader.java:188)
         at java.lang.ClassLoader.loadClass(ClassLoader.java:306)
         at java.lang.ClassLoader.loadClass(ClassLoader.java:251)
         at com.jutframe.JavaUnitTester.selectClass_actionPerformed(JavaUnitTester.java:449)
         at com.jutframe.JavaUnitTester$7.actionPerformed(JavaUnitTester.java:338)
         at javax.swing.AbstractButton.fireActionPerformed(AbstractButton.java:1849)
         at javax.swing.AbstractButton$Handler.actionPerformed(AbstractButton.java:2169)
         at javax.swing.DefaultButtonModel.fireActionPerformed(DefaultButtonModel.java:420)
         at javax.swing.DefaultButtonModel.setPressed(DefaultButtonModel.java:258)
         at javax.swing.AbstractButton.doClick(AbstractButton.java:302)
         at javax.swing.plaf.basic.BasicMenuItemUI.doClick(BasicMenuItemUI.java:1000)
         at javax.swing.plaf.basic.BasicMenuItemUI$Handler.mouseReleased(BasicMenuItemUI.java:1041)
         at java.awt.Component.processMouseEvent(Component.java:5488)
         at javax.swing.JComponent.processMouseEvent(JComponent.java:3093)
         at java.awt.Component.processEvent(Component.java:5253)
         at java.awt.Container.processEvent(Container.java:1966)
         at java.awt.Component.dispatchEventImpl(Component.java:3955)
         at java.awt.Container.dispatchEventImpl(Container.java:2024)
         at java.awt.Component.dispatchEvent(Component.java:3803)
         at java.awt.LightweightDispatcher.retargetMouseEvent(Container.java:4212)
         at java.awt.LightweightDispatcher.processMouseEvent(Container.java:3892)
         at java.awt.LightweightDispatcher.dispatchEvent(Container.java:3822)
         at java.awt.Container.dispatchEventImpl(Container.java:2010)
         at java.awt.Window.dispatchEventImpl(Window.java:1766)
         at java.awt.Component.dispatchEvent(Component.java:3803)
         at java.awt.EventQueue.dispatchEvent(EventQueue.java:463)
         at java.awt.EventDispatchThread.pumpOneEventForHierarchy(EventDispatchThread.java:234)
         at java.awt.EventDispatchThread.pumpEventsForHierarchy(EventDispatchThread.java:163)
         at java.awt.EventDispatchThread.pumpEvents(EventDispatchThread.java:157)
         at java.awt.EventDispatchThread.pumpEvents(EventDispatchThread.java:149)
         at java.awt.EventDispatchThread.run(EventDispatchThread.java:110)
                        JFileChooser jfilechooser=new JFileChooser();
                        Filterclass filter=new Filterclass();
                        //Set selection mode for file chooser
                        jfilechooser.setFileSelectionMode(JFileChooser.FILES_ONLY);
                        //set file filter
                        jfilechooser.setFileFilter(filter);
                        int returnVal = jfilechooser.showOpenDialog(this);
                        if(returnVal == JFileChooser.APPROVE_OPTION)
                            try
                                    String str = jfilechooser.getSelectedFile().getName();
                                    String parent=jfilechooser.getSelectedFile().getParent();
                                     // Create a File object on the root of the directory containing the class file
                                     File file = new File(parent);
                                     // Convert File to a URL
                                     URL url = file.toURL();         
                                     URL[] urls = new URL[]{url};
                                     // Create a new class loader with the directory
                                     ClassLoader cl = new URLClassLoader(urls);
                                     StringTokenizer st = new StringTokenizer(str,".");
                                     String s = st.nextToken ();
                                     Class c = cl.loadClass(s);  //ERROR IS SHOWN IN THIS PARTICULAR LINE
                                     Object instance=c.newInstance();
    --------------------------------------------please help me trace my mistake.
    thank you all.

    i think the problem that i have set a particular class path for my class files and my application loads files from that alone.
    So plz tell me if theres any way to access the class path of a particular file dynamically?
    regards

  • Excel import: importing too many rows

    I am working with SQL Developer 1.2.0 Build MAIN-29.98 and have a problem with Excel import: I would like to import some data from an XLS file. I click on Actions -> Import Data -> Excel, complete the dialog and check the DML: there are 3 insert into SQL statements that are correct (I can run them manually); however, SQL Developer imports not only 3 rows but much more! I cancelled the action after SQL Developer already imported 1015 rows!
    What am I doing wrong?
    Thanks!

    When I do a print preview I see only the rows and columns I entered, there is only one page. It seems that everything is ok in Excel.
    In the Excel import dialog SQL Developer correctly shows the preview of the content of the XLS file.
    Interestingly I often get a Java NullPointerException (local Java 6 JRE & JDK installation) when calling the Excel import dialog :(

  • Changing mouse pointer using setCursor()

    Hi- I've got a single threaded JFrame-based application in which I want to change the mouse pointer to indicate 'busy' when it's doing stuff eg. loading a file. So within my extended JFrame method for handling menu selections I've got:
    public class Layout extends JFrame
        // For items in the main menu
        // (the sub-class contains either a JMenuItem or JCheckBoxMenuItem).
        abstract class MenuItem implements ActionListener
            abstract JMenuItem menuItemAbs(); // get the menu item component
            abstract void handlerAbs(); // perform the menu's action
            // Menu item has been selected.
            public void actionPerformed(ActionEvent e)
                Cursor cursor = Layout.this.getCursor();
                Layout.this.setCursor(Cursor.getPredefinedCursor(Cursor.WAIT_CURSOR));
                handlerAbs();
                Layout.this.setCursor(cursor);
            }But the mouse pointer doesn't always change. If handler() just does some processing without user interaction, the pointer does change. But in the case of loading a file, where first the user selects the file using a JFileChooser, it doesn't.
    Is this because JFileChooser does its own setCursor()? But even if it does, presumably it does another setCursor() to restore my WAIT_CURSOR before it returns, so why don't I see the WAIT_CURSOR while the file is loading (which takes seconds)?
    Cheers
    John
    EDIT: BTW running under Linux, Java v6 update 7
    Edited by: matth1j on Nov 12, 2008 2:15 AM

    Ok, thanks - full demo program below.
    When you hit the ok button (just 5 second sleep), the mouse pointer changes to 'busy'. It reverts to normal if you move the pointer off the frame, but goes back to 'busy' if you move it back onto the frame.
    When you hit the bad button (brings up file chooser, then does 5 second sleep), the pointer changes to 'busy' while the pointer is over the frame, and reverts to normal when the pointer is moved off the frame. But if you select a file or cancel the file chooser and move the pointer back into the main frame before the 5 seconds is up, the pointer doesn't go back to 'busy' again. I would expect it to show 'busy' while over the frame until the 5 seconds is up.
    Any ideas?
    package test;
    import java.awt.Cursor;
    import java.awt.EventQueue;
    import java.awt.event.*;
    import javax.swing.*;
    public class Main
        public static void main(String[] args)
            EventQueue.invokeLater(new Runnable()
                public void run()
                    new Test();
    class Test extends JFrame
        public Test()
            super();
            this.setDefaultCloseOperation(EXIT_ON_CLOSE);
            JPanel panel = new JPanel();
            panel.add(new Button("ok"));
            panel.add(new Button("bad"));
            add(panel);
            pack();
            repaint();
            setVisible(true);
        class Button extends JButton implements ActionListener
            Button(String text)
                super(text);
                addActionListener(this);
            public void actionPerformed(ActionEvent e)
                Cursor cursor = Test.this.getCursor();
                Test.this.setCursor(Cursor.getPredefinedCursor(Cursor.WAIT_CURSOR));
                if (!e.getActionCommand().equals("ok"))
                    (new JFileChooser()).showOpenDialog(null);
                try
                    Thread.sleep(5000);
                catch (Exception ex)
                    ex.printStackTrace();
                Test.this.setCursor(cursor);
    }Edited by: matth1j on Nov 12, 2008 2:44 AM code tidy
    Edited by: matth1j on Nov 12, 2008 2:45 AM code tidy

Maybe you are looking for