JFileChooser nullPointerException.?

Hi all,
I can't seem to debug why I'm getting this error. The error is:
java.lang.NullPointerException
        at raphaelsebayhelper.TakeASeat.actionPerformed(TakeASeat.java:226)
        at javax.swing.AbstractButton.fireActionPerformed(AbstractButton.java:1786)
        at javax.swing.AbstractButton$ForwardActionEvents.actionPerformed(AbstractButton.java:1839)
        at javax.swing.DefaultButtonModel.fireActionPerformed(DefaultButtonModel.java:420)
        at javax.swing.DefaultButtonModel.setPressed(DefaultButtonModel.java:258)
        at javax.swing.plaf.basic.BasicButtonListener.mouseReleased(BasicButtonListener.java:245)
        at java.awt.Component.processMouseEvent(Component.java:5100)
        at java.awt.Component.processEvent(Component.java:4897)
        at java.awt.Container.processEvent(Container.java:1569)
        at java.awt.Component.dispatchEventImpl(Component.java:3615)
        at java.awt.Container.dispatchEventImpl(Container.java:1627)
        at java.awt.Component.dispatchEvent(Component.java:3477)
        at java.awt.LightweightDispatcher.retargetMouseEvent(Container.java:3483)
        at java.awt.LightweightDispatcher.processMouseEvent(Container.java:3198)
        at java.awt.LightweightDispatcher.dispatchEvent(Container.java:3128)
        at java.awt.Container.dispatchEventImpl(Container.java:1613)
        at java.awt.Window.dispatchEventImpl(Window.java:1606)
        at java.awt.Component.dispatchEvent(Component.java:3477)
        at java.awt.EventQueue.dispatchEvent(EventQueue.java:456)
        at java.awt.EventDispatchThread.pumpOneEventForHierarchy(EventDispatchThread.java:201)
        at java.awt.EventDispatchThread.pumpEventsForHierarchy(EventDispatchThread.java:151)
        at java.awt.EventDispatchThread.pumpEvents(EventDispatchThread.java:145)
        at java.awt.EventDispatchThread.pumpEvents(EventDispatchThread.java:137)
        at java.awt.EventDispatchThread.run(EventDispatchThread.java:100)And the error occurs here:
        else if(e.getSource() == fileChooserButton){
--> error line->      int returnval = emailFileChooser.showOpenDialog(this);
            if (returnval == JFileChooser.APPROVE_OPTION){
                File selectedFile = emailFileChooser.getSelectedFile();
                fileAndPathSelected.setText(selectedFile.getAbsolutePath());
        }I've setup my class like this:
public class TakeASeat extends JFrame implements ActionListener{
    private JFrame frame;
    private ImageIcon image = new ImageIcon("takeaseat.JPG");   
    private final JLabel headerFSLabel = new JLabel("", image, SwingConstants.CENTER);
    private JLabel createdBy = new JLabel("created by Sumeet Pathak");
    private Font buttonFont = new Font("Times New Roman", Font.BOLD, 14);
    private String currentDir = "";
    //button Panel
    private JButton kunden;
    private JButton item;
    private JButton orders;
    private JButton emailTransfer;
    // Email Transfer Panel
    private JPanel emailTrPanel;
    private JFileChooser emailFileChooser;
    private JButton fileChooserButton;
    private JTextField fileAndPathSelected;   
    /** Creates new form MyFrame */
    public TakeASeat() {
        frame = new JFrame("Take A Seat");
        Toolkit tk = Toolkit.getDefaultToolkit();
        Dimension d = tk.getScreenSize();
        int screenHeight = d.height;
        int screenWidth = d.width;
        int frameWidth = screenWidth * 2 / 3;
        int frameHeight = screenHeight * 2 / 3;
        frame.setBounds((screenWidth - frameWidth) / 2, (screenHeight - frameHeight) / 2, frameWidth, frameHeight);
        //frame.setResizable(false);
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        try {
            UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
        catch (Exception e){}
        frame.setDefaultLookAndFeelDecorated(true);
        //setup label header and buttons and MenuBar
        JMenuBar myMenuBar = createMenu();
        frame.setJMenuBar(myMenuBar);
        Container contentPane = frame.getContentPane();
        contentPane.add(headerFSLabel, BorderLayout.NORTH);
        contentPane.setBackground(Color.BLUE);
        JPanel bPanel = createButtonPanel();
        contentPane.add(bPanel, BorderLayout.WEST);
        //Display frame
        frame.setVisible(true);
    }That constructor creates my Frame, and adds a button panel on the left side. Now, when a button is clicked on this panel, a corresponding panel is shown at position BorderLayout.CENTER. It is on this panel that the JFileChooser resides. I've tried passing null into the showOpenDialog method and I still get the same result.
Does anyone see something I'm not? If you need more information, let me know what you need and I'll post it.
Thanks.
...DJVege...

Umm..ok! Note, this code is very messy (structure), but I figured I'd clean it up once I had everything running. Economize later. :-)
import javax.swing.*;
import javax.swing.JMenu;
import javax.swing.JMenuItem;
import javax.swing.JMenuBar;
import javax.swing.KeyStroke;
import javax.swing.border.*;
import java.awt.*;
import java.awt.Color;
import java.awt.event.*;
import java.io.*;
/*import java.awt.event.ActionListener;
import java.awt.event.ActionEvent;*/
* @author  Sum
public class TakeASeat extends JFrame implements ActionListener{
    private JFrame frame;
    private ImageIcon image = new ImageIcon("takeaseat.JPG");   
    private final JLabel headerFSLabel = new JLabel("", image, SwingConstants.CENTER);
    private JLabel createdBy = new JLabel("created by Sumeet Pathak");
    private Font buttonFont = new Font("Times New Roman", Font.BOLD, 14);
    private String currentDir = "";
    //button Panel
    private JButton kunden;
    private JButton item;
    private JButton orders;
    private JButton emailTransfer;
    // Email Transfer Panel
    private JPanel emailTrPanel;
    private JFileChooser emailFileChooser;
    private JButton fileChooserButton;
    private JLabel fileAndPathSelected;
    private JTextArea transferOutput;
    /** Creates new form MyFrame */
    public TakeASeat() {
        frame = new JFrame("Take A Seat");
        Toolkit tk = Toolkit.getDefaultToolkit();
        Dimension d = tk.getScreenSize();
        int screenHeight = d.height;
        int screenWidth = d.width;
        int frameWidth = screenWidth * 2 / 3;
        int frameHeight = screenHeight * 2 / 3;
        frame.setBounds((screenWidth - frameWidth) / 2, (screenHeight - frameHeight) / 2, frameWidth, frameHeight);
        //frame.setResizable(false);
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        try {
            UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
        catch (Exception e){}
        frame.setDefaultLookAndFeelDecorated(true);
        //setup label header and buttons and MenuBar
        JMenuBar myMenuBar = createMenu();
        frame.setJMenuBar(myMenuBar);
        Container contentPane = frame.getContentPane();
        contentPane.add(headerFSLabel, BorderLayout.NORTH);
        contentPane.setBackground(Color.BLUE);
        JPanel bPanel = createButtonPanel();
        contentPane.add(bPanel, BorderLayout.WEST);
        //Display frame
        frame.setVisible(true);
    private JMenuBar createMenu(){
        JMenuBar menuBar = new JMenuBar();
        JMenu file = new JMenu("File");
        file.setMnemonic(KeyEvent.VK_F);
        JMenuItem exit = new JMenuItem("Exit");
        exit.addActionListener(this);
        menuBar.add(file);
        file.add(exit);
        return menuBar;
    private void changePanel(JPanel panel){
        Container contentP = frame.getContentPane();
        contentP.add(panel, BorderLayout.CENTER);
        contentP.validate();
    private JPanel createButtonPanel(){
        JPanel buttonPanel = new JPanel();
        String panelHeader = "Functions";
        int headerJustification = TitledBorder.DEFAULT_JUSTIFICATION;
        int headerPosition = TitledBorder.DEFAULT_POSITION;
        Font headerFont = new Font("Times New Roman", Font.BOLD, 13);
        Border bPanelBorder = createBorder(panelHeader, headerJustification, headerPosition, headerFont, Color.WHITE);
        buttonPanel.setBorder(bPanelBorder);
        buttonPanel.setBackground(Color.BLUE.darker().darker());
        buttonPanel.setLayout(new GridLayout(6,1, 20, 15));
        kunden = new JButton("Kunden");
        kunden.setFont(buttonFont);
        kunden.addActionListener(this);
        item = new JButton("Items");
        item.setFont(buttonFont);
        item.addActionListener(this);
        orders = new JButton("Orders");
        orders.setFont(buttonFont);
        orders.addActionListener(this);
        emailTransfer = new JButton("Transfer");
        emailTransfer.setFont(buttonFont);
        emailTransfer.addActionListener(this);
        buttonPanel.add(kunden);
        buttonPanel.add(item);
        buttonPanel.add(orders);
        buttonPanel.add(emailTransfer);
        return buttonPanel;
     * Create the Kunden Panel containing the apporopriate fields/functions
    private JPanel emailTransferPanel(){
        // setup panel
        emailTrPanel = new JPanel();
        SpringLayout layout = new SpringLayout();
        emailTrPanel.setLayout(layout);
        emailTrPanel.setBackground(Color.LIGHT_GRAY);
        // Setup components in panel
        String emailTrHeader = "Transfter Data From Email File";
        int eTrheaderJust = TitledBorder.DEFAULT_JUSTIFICATION;
        int eTrheaderPos = TitledBorder.DEFAULT_POSITION;
        Font eTrheaderFont = new Font("Times New Roman", Font.BOLD, 13);
        Border emailTrBorder = createBorder(emailTrHeader, eTrheaderJust, eTrheaderPos, eTrheaderFont, Color.WHITE);
        emailTrPanel.setBorder(emailTrBorder);
        Font bFont = new Font("Times New Roman", Font.PLAIN, 14);       
        JLabel infoLabel = new JLabel("Select file to transfer details from");
        infoLabel.setFont(bFont);
        fileChooserButton = new JButton("Browse");
        fileChooserButton.setFont(bFont);
        Dimension bSize = new Dimension(150, 30);
        fileChooserButton.setPreferredSize(bSize);
        fileChooserButton.addActionListener(this);
        fileAndPathSelected = new JLabel();
        fileAndPathSelected.setBorder(BorderFactory.createCompoundBorder(BorderFactory.createEtchedBorder(), BorderFactory.createLoweredBevelBorder()));
        fileAndPathSelected.setBackground(Color.WHITE);
        fileAndPathSelected.setOpaque(true);
        fileAndPathSelected.setFont(bFont);
        Dimension textFieldSize = new Dimension(300, 30);
        fileAndPathSelected.setPreferredSize(textFieldSize);
        fileAndPathSelected.setFont(bFont);
        Dimension scrollPaneSize = new Dimension(400,200);       
        transferOutput = new JTextArea();
        transferOutput.setPreferredSize(scrollPaneSize);
        transferOutput.setMargin(new Insets(5,5,5,5));
        transferOutput.setEditable(false);
        transferOutput.setCursor(null);
        JScrollPane scrollPane = new JScrollPane(transferOutput, JScrollPane.VERTICAL_SCROLLBAR_ALWAYS,JScrollPane.HORIZONTAL_SCROLLBAR_ALWAYS);
        scrollPane.setPreferredSize(scrollPaneSize);
        JLabel outputLabel = new JLabel("Results");
        outputLabel.setFont(bFont);
        emailTrPanel.add(infoLabel);
        emailTrPanel.add(fileChooserButton);
        emailTrPanel.add(fileAndPathSelected);
        emailTrPanel.add(outputLabel);
        emailTrPanel.add(scrollPane);
        layout.putConstraint(SpringLayout.WEST, infoLabel, 10, SpringLayout.WEST, emailTrPanel);
        layout.putConstraint(SpringLayout.NORTH, infoLabel, 0, SpringLayout.NORTH, emailTrPanel);
        layout.putConstraint(SpringLayout.WEST, fileAndPathSelected, 10, SpringLayout.WEST, emailTrPanel);
        layout.putConstraint(SpringLayout.NORTH, fileAndPathSelected, 20, SpringLayout.NORTH, emailTrPanel);
        layout.putConstraint(SpringLayout.WEST, fileChooserButton, 5, SpringLayout.EAST, fileAndPathSelected);
        layout.putConstraint(SpringLayout.NORTH, fileChooserButton, 20, SpringLayout.NORTH, emailTrPanel);
        layout.putConstraint(SpringLayout.WEST, scrollPane, 30, SpringLayout.WEST, emailTrPanel);
        layout.putConstraint(SpringLayout.SOUTH, scrollPane, -10, SpringLayout.SOUTH, emailTrPanel);
        layout.putConstraint(SpringLayout.WEST, outputLabel, 30, SpringLayout.WEST, emailTrPanel);
        layout.putConstraint(SpringLayout.SOUTH, outputLabel, -5, SpringLayout.NORTH, scrollPane);
        return emailTrPanel;
    public void actionPerformed(ActionEvent e) {
        if (e.getSource() == kunden){
            emailTransfer.setEnabled(true);
            kunden.setEnabled(false);
            item.setEnabled(true);
            orders.setEnabled(true);           
            System.out.println("kunden");
        else if (e.getSource() == item){
            emailTransfer.setEnabled(true);
            kunden.setEnabled(true);
            item.setEnabled(false);
            orders.setEnabled(true);           
            System.out.println("item");
        else if (e.getSource() == orders){
            emailTransfer.setEnabled(true);
            kunden.setEnabled(true);
            item.setEnabled(true);
            orders.setEnabled(false);
            System.out.println("orders");
        else if (e.getSource() == emailTransfer){
            emailTransfer.setEnabled(false);
            kunden.setEnabled(true);
            item.setEnabled(true);
            orders.setEnabled(true);
            JPanel emailT = emailTransferPanel();
            changePanel(emailT);
            /*String msaccesspath = "F:\\Program Files\\Microsoft Office\\OFFICE11\\MSACCESS.EXE"; // path to MSACCESS.EXE
            String databasepath = "G:\\Raphael-Adresse-Kunden.mdb";
            EmailReader er = new EmailReader();         
            // Converting DBX file
            try {
                System.out.println("Please wait. Converting DBX file...");
                er.convertDBXFile();
                System.out.println("File converted successfully!");
            }catch(Exception ex){
                System.out.println("Error in converting" + "\n" + e);
                System.exit(0);
            // Extracting Data
            try {
                er.getData();
            } catch(Exception ex) {
                System.out.println("Error extracting data" + "\n" + e);
                System.exit(0);
            // Transfer to Database
            er.transferToDB();
            System.out.println("All Details transferred Successfully");*/         
        else if(e.getSource() == fileChooserButton){
            int returnval = emailFileChooser.showOpenDialog(this);
            if (returnval == JFileChooser.APPROVE_OPTION){
                File selectedFile = emailFileChooser.getSelectedFile();
                fileAndPathSelected.setText(selectedFile.getAbsolutePath());
    private Border createBorder(String borderTitle, int justification, int position, Font font, Color stringColour){
        Border etchedBorder = BorderFactory.createEtchedBorder();
        Border titleBorder = BorderFactory.createTitledBorder(etchedBorder, borderTitle, justification, position, font, stringColour);
        Border etchedAroundTitle = BorderFactory.createCompoundBorder(etchedBorder, titleBorder);
        Border emptyBorderInner = BorderFactory.createEmptyBorder(15, 15, 0, 15);
        Border emptyBorderOuter = BorderFactory.createEmptyBorder(5, 5, 0, 5);
        Border titleOutsideEmpty = BorderFactory.createCompoundBorder(titleBorder, emptyBorderInner);
        Border emptyOutsideTitle = BorderFactory.createCompoundBorder(emptyBorderOuter, titleOutsideEmpty);
        return emptyOutsideTitle;
     * @param args the command line arguments
    public static void main(String args[]) {
        java.awt.EventQueue.invokeLater(new Runnable() {
            public void run() {
                new TakeASeat();
    // Variables declaration - do not modify
    // End of variables declaration
}That should run.

Similar Messages

  • 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)

  • 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

  • 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 throws NullPointerException

    Dear all,
    Please check out the following code:
    JFileChooser addItemChooser = new JFileChooser();
    addItemChooser.setMultiSelectionEnabled(true);
    int returnVal = addItemChooser.showDialog( SAP_Functions.this, "Add" );     
    if (returnVal == JFileChooser.APPROVE_OPTION)
    File selectedFiles[] = listFileChooser.getSelectedFiles();
    When running the program i get the FileChooser but when i approve the selection the compiler gives me a NullPointerException message, what are the possible reasons for it?
    Thanks for your help.
    Kareem Naouri

    Looking at your code, I think what you mean to do is
    File[] selectedFiles = addItemChooser.getSelectedFiles();
    That is call getSelectedFiles() on the JFileChooser object that you have declared and instantiated within your code.

  • JFileChooser throws null pointer exception

    I'm using JFileChooser in my gui class. After I make my selection in the file chooser it sets off a null pointer exception. I'm running windows xp professiona. It was working perfectly fine till recently.
    My code for calling the chooser is:
        JFileChooser chooser = new JFileChooser();
        int returnVal = chooser.showOpenDialog(this);
        if(returnVal == chooser.APPROVE_OPTION){
          //setup the client now with the selected file to send
          client.setFile(chooser.getSelectedFile());
          jLabel5.setText(chooser.getSelectedFile().getName());
        }java.lang.NullPointerException
         at ftpresume.ClientGUI.jButton2_actionPerformed(ClientGUI.java:128)
         at ftpresume.ClientGUI_jButton2_actionAdapter.actionPerformed(ClientGUI.java:174)
         at javax.swing.AbstractButton.fireActionPerformed(AbstractButton.java:1786)
         at javax.swing.AbstractButton$ForwardActionEvents.actionPerformed(AbstractButton.java:1839)
         at javax.swing.DefaultButtonModel.fireActionPerformed(DefaultButtonModel.java:420)
         at javax.swing.DefaultButtonModel.setPressed(DefaultButtonModel.java:258)
         at javax.swing.plaf.basic.BasicButtonListener.mouseReleased(BasicButtonListener.java:245)
         at java.awt.Component.processMouseEvent(Component.java:5100)
         at java.awt.Component.processEvent(Component.java:4897)
         at java.awt.Container.processEvent(Container.java:1569)
         at java.awt.Component.dispatchEventImpl(Component.java:3615)
         at java.awt.Container.dispatchEventImpl(Container.java:1627)
         at java.awt.Component.dispatchEvent(Component.java:3477)
         at java.awt.LightweightDispatcher.retargetMouseEvent(Container.java:3483)
         at java.awt.LightweightDispatcher.processMouseEvent(Container.java:3198)
         at java.awt.LightweightDispatcher.dispatchEvent(Container.java:3128)
         at java.awt.Container.dispatchEventImpl(Container.java:1613)
         at java.awt.Window.dispatchEventImpl(Window.java:1606)
         at java.awt.Component.dispatchEvent(Component.java:3477)
         at java.awt.EventQueue.dispatchEvent(EventQueue.java:456)
         at java.awt.EventDispatchThread.pumpOneEventForHierarchy(EventDispatchThread.java:201)
         at java.awt.EventDispatchThread.pumpEventsForHierarchy(EventDispatchThread.java:151)
         at java.awt.EventDispatchThread.pumpEvents(EventDispatchThread.java:145)
         at java.awt.EventDispatchThread.pumpEvents(EventDispatchThread.java:137)
         at java.awt.EventDispatchThread.run(EventDispatchThread.java:100)

    I took a look at checking to see if the file is valid, exists, is readable and everything else. Looks like the file that's returned if fine. I'm not sure why my program crashes when I setup the file though. Here's my code from the client.setFile(File f);
    public void setFile(File f){
        if(f!=null){
          this.f = f;
          try {
            channel = new FileInputStream(f).getChannel();
            client.setupProgressBar(0,(int)f.length());
          }catch (FileNotFoundException e) {client.showError("FileNotFoundException: " + e);}
          catch(IOException e){client.showError("IOException: " + e);}
      }

  • Java.lang.NullPointerException javax.xml.parsers.DocumentBuilder.parse

    Hi all,
    i have a problem by solving an error in my code. The Code is mainly from Ian Darwin.
    The code i am running works with j2sdk1.4.2_04. But now i have to bring it to work with jdk1.6.0_13.
    The code parses xml documents. With small xml documents the code works. With large xml documents i get the following error while running the produced class file.
    Exception in thread "main" java.lang.NullPointerException
    at com.sun.org.apache.xerces.internal.dom.DeferredDocumentImpl.setChunkIndex(DeferredDocumentImpl.java:1944)
    at com.sun.org.apache.xerces.internal.dom.DeferredDocumentImpl.appendChild(DeferredDocumentImpl.java:644)
    at com.sun.org.apache.xerces.internal.parsers.AbstractDOMParser.characters(AbstractDOMParser.java:1191)
    at com.sun.org.apache.xerces.internal.impl.dtd.XMLDTDValidator.characters(XMLDTDValidator.java:862)
    at com.sun.org.apache.xerces.internal.impl.XMLDocumentFragmentScannerImpl.scanDocument(XMLDocumentFragmentScannerImpl.java:463)
    at com.sun.org.apache.xerces.internal.parsers.XML11Configuration.parse(XML11Configuration.java:807)
    at com.sun.org.apache.xerces.internal.parsers.XML11Configuration.parse(XML11Configuration.java:737)
    at com.sun.org.apache.xerces.internal.parsers.XMLParser.parse(XMLParser.java:107)
    at com.sun.org.apache.xerces.internal.parsers.DOMParser.parse(DOMParser.java:225)
    at com.sun.org.apache.xerces.internal.jaxp.DocumentBuilderImpl.parse(DocumentBuilderImpl.java:283)
    at javax.xml.parsers.DocumentBuilder.parse(DocumentBuilder.java:208)
    at XParse.parse(XParse.java:38)
    at XParse$JFileChooserrv.<init>(XParse.java:119)
    at XParse.main(XParse.java:213)
    I know what a java.lang.NullPointerException mens. But i don't know where i have to look for. Specially i don't know what or where "com.sun.org.apache...." is.
    Is there a package that a have to add to the environment? Can some one tell my where i can find this package?
    I wrote the code for some years ago, 2006 or so. With the knew jdk1.6.0_13 some thinks chance in the environment. Couldn't find what exactly.
    The code has only 215 lines, but some how i can't add it to this Message, because Maximum allowed is only 7500.
    Is there an other Forum, which may is better for my question?

    Here is the code:
    import java.io.*;
    import javax.xml.parsers.*;
    import org.w3c.dom.*;
    import org.xml.sax.*;
    import javax.swing.*;
    import java.awt.event.*;
    import java.io.*;
    import java.util.*;
    import javax.swing.*;
    import java.awt.Container;
    import javax.swing.JTextArea;
    * This code is mainly from @author Ian Darwin, [email protected]
    public class XParse {
         /** Convert the file */
         public static void parse(File file, boolean validate) {
              try {
                   System.err.println("");
                   String fileName = file.getAbsolutePath();
                   System.err.println("Parsing " + fileName + "...");
                   // Make the document a URL so relative DTD works.
                   //String uri = new File(fileName).getAbsolutePath();
                   //System.err.println(uri);
                   DocumentBuilderFactory f = DocumentBuilderFactory.newInstance();
                   if (validate)
                   f.setValidating(true);
                   DocumentBuilder p = f.newDocumentBuilder();
                   p.setErrorHandler(new MyErrorHandler(System.err));
                   //XmlDocument doc = XmlDocument.createXMLDocument(file);
                   boolean vaild =  p.isValidating();
                   if (vaild) {
                        System.out.println("yes parsing");
                        Document doc = p.parse(file); // <<<< ERROR
                   System.out.println("Parsed OK");
              } catch (SAXParseException ex) {
                   System.err.println("+================================+");
                   System.err.println("|       *SAX Parse Error*        |");
                   System.err.println("+================================+");
                   System.err.println(ex.toString());
                   System.err.println("At line " + ex.getLineNumber());
                   System.err.println("+================================+");
              } /**catch (RuntimeException ex) {
                   System.err.println("+================================+");
                   System.err.println("|       *SAX Parse Error*        |");
                   System.err.println("+================================+");
                   System.err.println(ex.toString());
                   //System.err.println("At line " + ex.getLineNumber());
                   //System.err.println("At line " + ex.getMessage());
                   System.err.println("+================================+");
              }**/ catch (SAXException ex) {
                   System.err.println("+================================+");
                   System.err.println("|          *SAX Error*           |");
                   System.err.println("+================================+");
                   System.err.println(ex.toString());
                   System.err.println("+================================+");
              /*}} catch (SAXNotRecognizedException  ex) {
                   System.err.println(" no SAX");*/
              } catch (ParserConfigurationException ex) {
                   System.err.println(" ???");
               } catch (IOException ex) {
                   System.err.println("+================================+");
                   System.err.println("|           *XML Error*          |");
                   System.err.println("+================================+");
                   System.err.println(ex.toString());
    private static class JFileChooserrv {
         JFileChooserrv(JFrame f, boolean vverabreiten) {
              String openfile;
              String verror;
              boolean validate = true;
              final JFrame frame = f;
              String vFilename = "Z:\\Boorberg\\parsen_vista\\daten";
              //String vFilename = "C:\\";
              File vFile = new File(vFilename);
              final JFileChooser chooser = new JFileChooser(vFile);
              JFileFilter filter = new JFileFilter();
              filter.addType("xml");
              filter.addType("sgml");
              filter.addType("html");
              filter.addType("java");
              filter.setDescription("strukturfiles");
              chooser.addChoosableFileFilter(filter);
              boolean vjeas = true;
              chooser.setMultiSelectionEnabled(vjeas);
              int returnVal = chooser.showOpenDialog(frame);
              if (returnVal == JFileChooser.APPROVE_OPTION) {
                   //Array  filearry[] = chooser.getSelectedFiles();
                   //if (vFile = chooser.getSelectedFiles()) {
                   //File  file[] = chooser.getSelectedFiles();
                   File  vfile[] = chooser.getSelectedFiles();
                   //String openfile = new String();
                   int vlenght = vfile.length;
                   if (vlenght>1) {
                        int x=0;
                        while (x< vlenght) {
                                  parse(vfile[x], validate);
                                  x = x +1;
                   if (vlenght<=1) {
                        File v2file = chooser.getSelectedFile();
                             parse(v2file, validate);
              } else {
                   System.out.println("You did not choose a filesystem           object.");
         System.exit(0);
    private static class JFileFilter extends javax.swing.filechooser.FileFilter {
         protected String description, vnew;
         protected ArrayList<String> exts = new ArrayList<String>();
         protected boolean vtrue;
         public void addType(String s) {
              exts.add(s);
         /** Return true if the given file is accepted by this filter. */
         public boolean accept(File f) {
              // Little trick: if you don't do this, only directory names
              // ending in one of the extentions appear in the window.
              if (f.isDirectory()) {
                   return true;
              } else if (f.isFile()) {
                   Iterator it = exts.iterator();
                   while (it.hasNext()) {
                        if (f.getName().endsWith((String)it.next()))
                             return true;
              // A file that didn't match, or a weirdo (e.g. UNIX device file?).
              return false;
         /** Set the printable description of this filter. */
         public void setDescription(String s) {
              description = s;
         /** Return the printable description of this filter. */
         public String getDescription() {
              return description;
    private static class MyErrorHandler implements ErrorHandler {
            // Error handler output goes here
            private PrintStream out;
            MyErrorHandler(PrintStream out) {
                this.out = out;
             * Returns a string describing parse exception details
            private String getParseExceptionInfo(SAXParseException spe) {
                String systemId = spe.getSystemId();
                if (systemId == null) {
                    systemId = "null";
                String info = "URI=" + systemId +
                    " Line=" + spe.getLineNumber() +
                    ": " + spe.getMessage();
                return info;
            // The following methods are standard SAX ErrorHandler methods.
            // See SAX documentation for more info.
            public void warning(SAXParseException spe) throws SAXException {
                   //System.exit(0);
                //out.println("Warning: " + getParseExceptionInfo(spe));
            public void error(SAXParseException spe) throws SAXException {
                   //System.exit(0);
                String message = "Error: " + getParseExceptionInfo(spe);
                throw new SAXException(message);
            public void fatalError(SAXParseException spe) throws SAXException {
                   //System.exit(0);
                String message = "Fatal Error: " + getParseExceptionInfo(spe);
                throw new SAXException(message);
         public static void main(String[] av) {
              JFrame vframe = new JFrame("chose files to pars");
              boolean vverabreiten = true;
              boolean validate = true;
              JFileChooserrv vdateienwaehlen = new JFileChooserrv(vframe, vverabreiten);
    }The Stack Trace i posted in the last Message. But i couldn't read it, i am not a programmer.

  • JFileChooser : Exception occurred during event dispatching

    Hi,
    I'm having problems with sorting in 'Details' view of JFileChooser. I'm getting the following NullPointerException when I try to sort by clicking on the header of the JTable which I get in 'Details' view of a JFileChooser.
    Exception occurred during event dispatching:
    java.lang.NullPointerException
    at java.awt.EventQueue.isDispatchThread(Unknown Source)
    at javax.swing.SwingUtilities.isEventDispatchThread(Unknown Source)
    at javax.swing.JComponent.revalidate(Unknown Source)
    at javax.swing.JTable.resizeAndRepaint(Unknown Source)
    at javax.swing.JTable.sortedTableChanged(Unknown Source)
    at javax.swing.JTable.sorterChanged(Unknown Source)
    at javax.swing.RowSorter.fireRowSorterChanged(Unknown Source)
    at javax.swing.RowSorter.fireRowSorterChanged(Unknown Source)
    at javax.swing.DefaultRowSorter.sort(Unknown Source)
    at sun.swing.FilePane$DetailsTableRowSorter.access$1301(Unknown Source)
    at sun.swing.FilePane$DetailsTableRowSorter$1.call(Unknown Source)
    at sun.swing.FilePane$DetailsTableRowSorter$1.call(Unknown Source)
    at java.util.concurrent.FutureTask$Sync.innerRun(Unknown Source)
    at java.util.concurrent.FutureTask.run(Unknown Source)
    at java.util.concurrent.ThreadPoolExecutor$Worker.runTask(Unknown Source)
    at java.util.concurrent.ThreadPoolExecutor$Worker.run(Unknown Source)
    at sun.awt.shell.Win32ShellFolderManager2$ComInvoker$3.run(Unknown Source)
    at java.lang.Thread.run(Unknown Source)
    Any operation performed in the JFileChooser after this exception will generate the same exception & no action is performed. I'm using Java 1.6.0_24. Strangely, this is happening only in client-server mode. Staand-alone is working fine.
    Please provide some urgent inputs to this problem
    Thanks
    Dilip

    Thanks 4 d reply mKorbel, I'm not creating a TableModel. I'm just creating a JFileChooser as shown below.
    JFileChooser fileChooser = new JFileChooser(location);
    fileChooser.setFileSelectionMode(JFileChooser.FILES_ONLY);
    fileChooser.setMultiSelectionEnabled(false);
    fileChooser.setDialogTitle("Choose File");
    if (fileChooser.showOpenDialog(null) == JFileChooser.APPROVE_OPTION)
    Now, the scenario is to bringup the FileChooser, go to Details view, apply sort on any column. This action creates the mentioned NullPointerException.

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

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

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

  • Problem with the JFileChooser

    Hello all,
    I'm having a small problem with the JFileChooser, the thing is whenever I click the cancel button in the dialog box a NullPointerException is thrown, so does anyone know wut is wrong?

    Either way, it's an extremely important skill to learn to read the API and become familiar with the tools you will use to program Java. Java has an extensive set of documentation that you can even download for your convenience. These "javadocs" are indexed and categorized so you can quickly look up any class or method. Take the time to consult this resource whenever you have a question - you'll find they typically contain very detailed descriptions and possibly some code examples.
    Java� API Specifications
    Java� 1.5 JDK Javadocs
    Best of luck!
    ~

  • Changing L&F for the JFileChooser

    Hi,
    take a look at Sun's bug #4711700. Using the Windows L&F, sometimes the JFileChooser throws a NullPointerException when the constructor is called.
    Apparently, the bug is related to retrieving Windows system icons to be shown in the dialog, so it's probably not there when using a non Windows L&F.
    As my app needs to use the L&F of the host OS, I was thinking about using a workaround like this:
    JFileChooser jfc;
    try {
      jfc = new JFileChooser(...);
    } catch(NullPointerException ex) {
      /* change L&F for file chooser here */
      jfc = new JFileChooser();
    }This may not be very appealing, but it's definitely better than the exception!
    The question is: it possible to selectively change the L&F for the file chooser, without affecting the rest of the components, and how do I do it?

    JFileChooser fileChooser=new JFileChooser();// to choose the file ExampleFileFilter filter = new ExampleFileFilter();// to make file settings
         filter.addExtension("jpeg");
         filter.addExtension("jpg");
         filter.setDescription("Image Format");
         fileChooser.setFileFilter(filter);//new File(".")
         fileChooser.setCurrentDirectory(new File("."));
         int result = fileChooser.showOpenDialog(printFrame);//to open dialog box
         if(result==JFileChooser.CANCEL_OPTION)
                   file=null;
    try this u can solve ur problem and , write example filter class
    //ExampleFilter.java
    import java.io.File;
    import java.util.Hashtable;
    import java.util.Enumeration;
    import javax.swing.filechooser.*;
    public class ExampleFileFilter extends FileFilter {
    private static String TYPE_UNKNOWN = "Type Unknown";
    private static String HIDDEN_FILE = "Hidden File";
    private Hashtable filters = null;
    private String description = null;
    private String fullDescription = null;
    private boolean useExtensionsInDescription = true;
    public ExampleFileFilter() {
              this.filters = new Hashtable();
    public ExampleFileFilter(String extension) {
         this(extension,null);
    public ExampleFileFilter(String extension, String description) {
         this();
         if(extension!=null) addExtension(extension);
         if(description!=null) setDescription(description);
    public ExampleFileFilter(String[] filters) {
         this(filters, null);
    public ExampleFileFilter(String[] filters, String description) {
         this();
         for (int i = 0; i < filters.length; i++) {
         addExtension(filters);
         if(description!=null) setDescription(description);
    public boolean accept(File f) {
         if(f != null) {
         if(f.isDirectory()) {
              return true;
         String extension = getExtension(f);
         if(extension != null && filters.get(getExtension(f)) != null) {
              return true;
         return false;
    public String getExtension(File f) {
         if(f != null) {
         String filename = f.getName();
         int i = filename.lastIndexOf('.');
         if(i>0 && i<filename.length()-1) {
              return filename.substring(i+1).toLowerCase();
         return null;
    public void addExtension(String extension) {
         if(filters == null) {
         filters = new Hashtable(5);
         filters.put(extension.toLowerCase(), this);
         fullDescription = null;
    public String getDescription() {
         if(fullDescription == null) {
         if(description == null || isExtensionListInDescription()) {
              fullDescription = description==null ? "(" : description + " (";
              // build the description from the extension list
              Enumeration extensions = filters.keys();
              if(extensions != null) {
              fullDescription += "." + (String) extensions.nextElement();
              while (extensions.hasMoreElements()) {
                   fullDescription += ", ." + (String) extensions.nextElement();
              fullDescription += ")";
         } else {
              fullDescription = description;
         return fullDescription;
    public void setDescription(String description) {
         this.description = description;
         fullDescription = null;
    public void setExtensionListInDescription(boolean b) {
         useExtensionsInDescription = b;
         fullDescription = null;
    public boolean isExtensionListInDescription() {
         return useExtensionsInDescription;
    try this u can solve ur problem and , write example filter class
    cheers
    nr konjeti

  • JFileChooser and remote filesystems

    I want to add(among local file system) a few remote filesystems to JFileChooser ,
    I implemented FileSytestemVIew(FileSystem) and File(RemoteFile) class.
    At the first glance everything looks ok - i can see local folders and remote root folder(in combo box), when i choose remote root i can see remote folders and files, but when i invoke double click to enter remote folders, exception occurs.
    for some reason JFileChooser sees 'ordinary' File - not my RemoteFile, and it treats it as a file (not folder) and wants to open it (approveSelection fires)
    Probably i did not implemented all the methods that are used ..
    Any ideas ? maybe there are some other ways to explore remote filesystems ?
    package pl.edu.pw.browser;
    import javax.swing.filechooser.FileSystemView;
    import java.io.File;
    import java.io.IOException;
    import pl.edu.pw.fileserver.client.Client;
    import java.util.*;
    import javax.swing.Icon;
    public class FileSystem extends FileSystemView {
    public FileSystem(ArrayList servers) {
    this.servers=servers;
    public File createFileObject(File dir, String filename) {
    System.out.println("createFileObject1");
    if (dir instanceof RemoteFile )
    return new RemoteFile(((RemoteFile)dir).getFtp(),dir.getAbsolutePath(), filename);
    return super.createFileObject(dir,filename);
    public boolean isDrive(File dir)
    if (dir instanceof RemoteFile )
    return false;
    return super.isDrive(dir);
    public boolean isFloppyDrive(File dir)
    if (dir instanceof RemoteFile )
    return false;
    return super.isFloppyDrive(dir);
    public boolean isComputerNode(File dir)
    if (dir instanceof RemoteFile)
    if(servers.contains(dir))
    return true;
    else
    return false;
    return super.isComputerNode(dir);
    public File createFileObject(String path) {
    return null;
    public boolean isFileSystem(File f) {
    System.out.println("isFileSystem");
    if (f instanceof RemoteFile) {
    return false;
    } else
    return super.isFileSystem(f);
    public boolean isFileSystemRoot(File dir)
    System.out.println("isFileSystemRoot");
    if (dir instanceof RemoteFile)
    if(servers.contains(dir))
    return true;
    else
    return false;
    return super.isFileSystemRoot(dir);
    public boolean isRoot(File f) {
    System.out.println("isRoot");
    if (f instanceof RemoteFile )
    if(servers.contains(f))
    return true;
    else
    return false;
    return super.isRoot(f);
    public String getSystemTypeDescription(File f)
    if (f instanceof RemoteFile)
    return f.getName();
    return super.getSystemTypeDescription(f);
    public Icon getSystemIcon(File f)
    return super.getSystemIcon(f);
    public boolean isParent(File folder,
    File file)
    if (folder instanceof RemoteFile && file instanceof RemoteFile )
    System.out.println("isParent("+folder.getAbsolutePath()+")("+file.getAbsolutePath()+")");
    if(file.getParent().equals(folder.getAbsolutePath()))
    System.out.println("is");
    return true;
    else
    return false;
    return super.isParent(folder,file);
    public File getChild(File parent,
    String fileName)
    System.out.println("getChild");
    if (parent instanceof RemoteFile )
    return new RemoteFile(((RemoteFile)parent).getFtp(),parent.getAbsolutePath(),fileName);
    return super.getChild(parent,fileName);
    public File createNewFolder(File containingDir)
    throws IOException {
    System.out.println("createNewFolder");
    if (containingDir instanceof RemoteFile )
    return null;
    return new File(containingDir,"/nowyFolder");
    public String getSystemDisplayName(File f)
    if (f instanceof RemoteFile )
    return f.getName();
    else
    return super.getSystemDisplayName(f);
    public File[] getRoots()
    System.out.println("getRoots");
    File[] files = super.getRoots();
    File[] fileAll = new File[files.length+1];
    int i=0;
    for(i=0;i<files.length;i++)
    fileAll=files[i];
    fileAll[i]=createFileSystemRoot((RemoteFile)servers.get(0));
    return fileAll;
    public boolean isHiddenFile(File f) {
    return f.isHidden();
    public File getParentDirectory(File dir) {
    System.out.println("getParentDirectory");
    if (dir instanceof RemoteFile)
    String p = dir.getParent();
    if(p!=null)
    return new RemoteFile(((RemoteFile)dir).getFtp(),p);
    else
    return null;
    else
    return super.getParentDirectory(dir);
    protected File createFileSystemRoot(File f)
    System.out.println("createFileSystemRoot");
    if (f instanceof RemoteFile)
    return new FileSystemRoot( (RemoteFile) f);
    else
    return super.createFileSystemRoot(f);
    static class FileSystemRoot extends RemoteFile {
    public FileSystemRoot(RemoteFile f) {
    super(f.getFtp(),f.getAbsolutePath());
    public File[] getFiles(File dir, boolean useFileHiding) {
    if (dir instanceof RemoteFile)
    RemoteFile[] files = (RemoteFile[])( (RemoteFile) dir).listFiles();
    return files;
    else
    return dir.listFiles();
    public File getHomeDirectory() {
    return super.getHomeDirectory();
    ArrayList servers = null;
    package pl.edu.pw.browser;
    import java.io.File;
    import java.io.FilenameFilter;
    import java.io.FileFilter;
    import pl.edu.pw.fileserver.client.Client;
    import java.util.*;
    import java.text.*;
    import pl.edu.pw.fileserver.Constants;
    public class RemoteFile extends File {
    final static char PATHDELIMS = '/';
    public final static String absoluteStart = "//";
    public RemoteFile(Client ftp, String parent) {
    super(parent);
    this.ftp = ftp;
    path = parent;
    public RemoteFile(Client ftp, String parent, String name) {
    this(ftp, parent);
    if (path.length()>0 && path.charAt(path.length()-1) == PATHDELIMS)
    path += name;
    else
    path += PATHDELIMS + name;
    public boolean equals(Object obj) {
    if (!checked)
    exists();
    return path.equals(obj.toString());
    public boolean isDirectory() {
    if (!checked)
    exists();
    return isdirectory;
    public boolean isFile() {
    if (!checked)
    exists();
    return isfile;
    public boolean isAbsolute() {
    if (!checked)
    exists();
    return path.length() > 0 && path.startsWith(this.absoluteStart);
    public boolean isHidden() {
    if (!checked)
    exists();
    return ishidden;
    public long lastModified() {
    return modified;
    public long length() {
    return length;
    public String[] list() {
    return list(null);
    public String[] list(FilenameFilter filter) {
    System.out.println("list");
    String[] result = null;
    try{
    ArrayList names = (ArrayList)ftp.dir(this.getAbsolutePath());
    ArrayList files = new ArrayList();
    for(int i=0;i<names.size();i++)
    RemoteFile rf = new RemoteFile(ftp,(String)names.get(i));
    if (filter == null || filter.accept(this,rf.getName()))
    files.add(rf.getName());
    result = new String[files.size()];
    files.toArray(result);
    catch(Exception ex)
    ex.printStackTrace();
    return result;
    public File[] listFiles() {
    FileFilter filter = null;
    return listFiles(filter);
    public File[] listFiles(FileFilter filter) {
    System.out.println("listFiles");
    RemoteFile[] result = null;
    try{
    ArrayList names = (ArrayList)ftp.dir(this.getAbsolutePath());
    ArrayList files = new ArrayList();
    for(int i=0;i<names.size();i++)
    RemoteFile rf = new RemoteFile(ftp,(String)names.get(i));
    rf.exists();
    if (filter == null || filter.accept(rf))
    files.add(rf);
    result = new RemoteFile[files.size()];
    System.out.println("listFiles.size="+files.size());
    files.toArray(result);
    catch(Exception ex)
    ex.printStackTrace();
    return result;
    public String getPath() {
    return path;
    public String getCanonicalPath() {
    return getAbsolutePath();
    public String getAbsolutePath() {
    if (!isAbsolute()) {
    return ftp.pwd();
    return path;
    public String getName() {
    String result=path;
    if(result.charAt(result.length()-1) == this.PATHDELIMS)
    result = result.substring(0,result.length()-1);
    int i = result.lastIndexOf(this.PATHDELIMS);
    if(i!=-1)
    result = result.substring(i+1);
    return result;
    public String getParent() {
    String result=path;
    if(result.charAt(result.length()-1) == this.PATHDELIMS)
    result = result.substring(0,result.length()-1);
    int i = result.lastIndexOf(this.PATHDELIMS);
    if(i<3)
    return null;
    result = result.substring(0,i);
    return result;
    public boolean exists() {
    boolean ok = false;
    try {
    String r = ftp.exists(path);
    if(r != null)
    System.out.println("('"+path+"')header:"+r);
    ok = true;
    StringTokenizer st = new StringTokenizer(r,Constants.HEADER_SEPARATOR);
    String answer = st.nextToken();
    if(answer.equals(Constants.TRUE))
    isfile=true;
    isdirectory=false;
    answer = st.nextToken();
    if(answer.equals(Constants.TRUE))
    canread = true;
    answer = st.nextToken();
    if(answer.equals(Constants.TRUE))
    canwrite = true;
    answer = st.nextToken();
    if(answer.equals(Constants.TRUE))
    ishidden = true;
    answer = st.nextToken();
    length = Long.parseLong(answer);
    if(isfile)
    answer = st.nextToken();
    modified = Long.parseLong(answer);
    checked = true;
    catch (Exception ex) {
    ex.printStackTrace();
    return ok;
    public boolean canRead() {
    return canread;
    public boolean canWrite() {
    return canwrite;
    public int hashCode() {
    return path.hashCode() ^ 098123;
    public boolean mkdir() {
    return false;
    public boolean renameTo(File dest) {
    return false;
    public Client getFtp() {
    return ftp;
    private Client ftp;
    private boolean checked = false;
    private boolean isdirectory = true;
    private boolean isfile = false;
    private boolean ishidden = false;
    private boolean canread = false;
    private boolean canwrite = false;
    private String path;
    private long length = 0;
    private long modified =0;
    java.lang.NullPointerException
         at pl.edu.pw.browser.Browser.openLocalFile(Browser.java:136)
         at pl.edu.pw.browser.component.FileChooser.approveSelection(FileChooser.java:31)
         at javax.swing.plaf.basic.BasicFileChooserUI$DoubleClickListener.mouseClicked(BasicFileChooserUI.java:412)
         at java.awt.AWTEventMulticaster.mouseClicked(AWTEventMulticaster.java:208)
         at java.awt.AWTEventMulticaster.mouseClicked(AWTEventMulticaster.java:207)
         at java.awt.Component.processMouseEvent(Component.java:5137)
         at java.awt.Component.processEvent(Component.java:4931)
         at java.awt.Container.processEvent(Container.java:1566)
         at java.awt.Component.dispatchEventImpl(Component.java:3639)
         at java.awt.Container.dispatchEventImpl(Container.java:1623)
         at java.awt.Component.dispatchEvent(Component.java:3480)
         at java.awt.LightweightDispatcher.retargetMouseEvent(Container.java:3450)
         at java.awt.LightweightDispatcher.processMouseEvent(Container.java:3174)
         at java.awt.LightweightDispatcher.dispatchEvent(Container.java:3095)
         at java.awt.Container.dispatchEventImpl(Container.java:1609)
         at java.awt.Window.dispatchEventImpl(Window.java:1590)
         at java.awt.Component.dispatchEvent(Component.java:3480)
         at java.awt.EventQueue.dispatchEvent(EventQueue.java:450)
         at java.awt.EventDispatchThread.pumpOneEventForHierarchy(EventDispatchThread.java:197)
         at java.awt.EventDispatchThread.pumpEventsForHierarchy(EventDispatchThread.java:150)
         at java.awt.EventDispatchThread.pumpEvents(EventDispatchThread.java:144)
         at java.awt.EventDispatchThread.pumpEvents(EventDispatchThread.java:136)
         at java.awt.EventDispatchThread.run(EventDispatchThread.java:99)

    i solve the problem .
    I did not overwrite File.getConicalFile() , this method is invoked at javax.swing.plaf.basic.BasicFileChooserUI$DoubleClickListener.mouseClicked(BasicFileChooserUI.java:412)
    that is why i recived a new object type File when I was waiting for RemoteFile

  • 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() );

  • JFileChooser leaks memory -  HELP

    Hi all,
    I am having difficulty with this. I am using Borland Optimizit. I can see two instances of my object and two instances of JFileChooser.
    See below method: If I browse there is no leak. If I enter the if block it leaks.
    public final void actionPerformed(ActionEvent evt)
    // get the event source
    Object source = evt.getSource();
    // if the event source is the browse button
    if(source == browseButton)
    // if the file chooser has not been instantiated
    if(fileChooser == null)
    fileChooser = new JFileChooser();
    // allow the user to browse the directories
    fileChooser.setCurrentDirectory(new File(Const.DEFAULT_DIRECTORY));
    int result = fileChooser.showOpenDialog(this);
    // if the user selected a file
    if(result == JFileChooser.APPROVE_OPTION)
         // The try block is necessary because the showOpenDialog method
         // returns APPROVE_OPTION if the user clicks open without
         // selecting a file. This will cause the
         // JFileChooser.getSelectedFile method to throw a
         // NullPointerException.
         try
         // set the text in the file name text field to the name of
    // the file selected
         String f = fileChooser.getSelectedFile().getAbsolutePath();
         fileTextField.setText(f);
         catch(NullPointerException e)
         // Do nothing. The file name text field will be left
         // unchanged.
    }// end actionPerformed()

    http://search.java.sun.com/search/java/index.jsp?qp=&nh=10&qt=%2Bjfilechooser+%2B%22memory+leak%22&col=javabugs&col=javaforums&x=24&y=13

  • Problems with JFileChooser

    I looked thru the bug database and forums but didn't see anything quite like this. I have JFileChooser that I use for a user to select an input test case (XML file) and optionally select an output directory. The trouble is, for some reason, the output directory text value is being corrupted, the last occurrence of the file.seperator is being dropped i.e. instead of getting c:\dir1\dir2\dir3, I am getting c:\dir1\dir2dir3. The code I use is shown below. Am I doing something stupid or is there something else going on? Cheers, Max
            smt.fcOutButton.addActionListener(new ActionListener()
                 public void actionPerformed(ActionEvent ae)
                                  JFileChooser fc = new JFileChooser();
                                  fc.setFileSelectionMode(JFileChooser.DIRECTORIES_ONLY);
                                  fc.showOpenDialog(smt.frame);
                                  try
                                       String filename = fc.getSelectedFile().getPath();
                                       smt.outFileText.setText(filename);
                                       smt.outDir = fc.getSelectedFile().getParent() +
                                            fc.getSelectedFile().getName() +
                                            System.getProperty("file.separator");
                                       System.out.println(smt.outDir);
                                  catch (NullPointerException npe)
            });

    instead of System.getProperty("file.seperator")
    i use
    File.separator
    or
    File.separatorChar
    then I don't have to call the System.getProperty() method.
    have used it on Linux and Windows.

Maybe you are looking for

  • How can I have my emails on iPhone4 and and the mail app on Macbook?

    I currently have a Yahoo email address which I had before having my iPhones...and now I have a Macbook Pro. How can I get my emails to be visible on my iPhone mail app and the mail app on the Macbook? Before I attempt it, if I add this mail account t

  • HT200154 Apple TV onkyo tx-sr576 TV - why doesn't it work?

    Hi all. Just tried setting up my new ATV, but try as I might, I can't get it to work when I route the hdmi cable through the receiver. It works fine when going just to the TV, but I only use the TV as a monitor so I get no sound doing it that way, pl

  • Convert __DIR__ to standard url

    hi i want to use a file from javafx in java code. the path of the file defined in javafx is using the "__DIR__" variable. please tell me how can i convert this into standard url (i.e c:\xxx.jpg). because when i am using __DIR__ the string is coming l

  • Upgrading MAC OS X 10.3 to 10.4 on 350MHz Power PC

    I just finished installing a new HD in my old 350 MHz PowerPC G3 & have OS X 10.3.9 loaded up but want to upgrade to 10.4 or better. The G3 does not have firewire & it looks as if that is a requirement for 10.4. Does anyone have any input on if I can

  • Reg:Time stamp in DB TABLE

    Hi Can any one please lemme know how to find the time for which an entry in a db table is inserted or modified if the db table dnt have the time field?? Thanks and Regards Arun Joseph