AddMouseListener to FilePane in JFileChooser

I'm having problem in adding a MouseListener to FilePane of JFileChooser.
My end goal is: show my own PopupMenu in FilePane, but I can't handle the MouseEvent, FilePane always show its default PopupMenu, bypass my mouse handler.
I really need someone's help, coz I have worked on this for days, but :( SOS pls
I use this for Local File Browsing on my FTP Client App, like CuteFTP.
I can show a simple example code here:
/*Class fileChooser_Frame, include main() method*/
import java.awt.BorderLayout;
import javax.swing.JFrame;
import sun.swing.FilePane;
import javax.swing.JFileChooser;
import java.awt.event.MouseListener;
import java.awt.event.MouseEvent;
import javax.swing.JPanel;
import javax.swing.JComponent;
import javax.swing.JList;
import java.awt.Point;
import javax.swing.JPopupMenu;
import javax.swing.JMenuItem;
public class fileChooser_Frame extends JFrame {
    BorderLayout borderLayout1 = new BorderLayout();
    public fileChooser_Frame() {
        try {
            jbInit();
        } catch (Exception exception) {
            exception.printStackTrace();
    private void jbInit() throws Exception {
        getContentPane().setLayout(borderLayout1);
        JFileChooser jF = new JFileChooser();
        FilePane filePane = (FilePane) jF.getComponent(2);
        final JPopupMenu jPop = new JPopupMenu("Testing");
        JMenuItem jMenuItem = new JMenuItem("Item 1");
        jPop.add(jMenuItem);
        MouseListener mouseListener  = new MouseListener(){
            public void mouseClicked(MouseEvent e) {
                System.out.println("Mouse Clicked");
                checkPopup(e);
            public void mousePressed(MouseEvent e) {
                System.out.println("Mouse Pressed");
                checkPopup(e);
            public void mouseReleased(MouseEvent e) {
                System.out.println("Mouse Released");
                checkPopup(e);
            public void mouseEntered(MouseEvent e) {
            public void mouseExited(MouseEvent e) {
            private void checkPopup(MouseEvent e){
                 if(e.isPopupTrigger())
                     jPop.show(e.getComponent(),e.getX(),e.getY());
        filePane.addMouseListener(mouseListener);
        getContentPane().add(filePane, BorderLayout.CENTER);
/*The result here is: FilePane show only its default PopupMenu, not my jPop :((, I need help here, pls*/
    public static void main(String[] args) {
        fileChooser_Frame filechooser_frame = new fileChooser_Frame();                                                                                 filechooser_frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        filechooser_frame.pack();
        filechooser_frame.setVisible(true);
}

Just another cross poster.
[http://www.javavietnam.org/javavn/mvnforum/viewthread_thread,22962]
[http://www.dreamincode.net/forums/showtopic68532.htm]
db
edit And
[http://www.java-forums.org/awt-swing/11787-how-use-jfilechooser-select-file-string.html]
Edited by: Darryl.Burke

Similar Messages

  • How to add Mouse Listener

    here is my code for my current project, it is to create a platform independent way to have a windows explore like window so far I have it displaying properly and all I need to do is when the user double clicks on a file itt should open up but thats where i need help, this is not homework
    import java.awt.*;
    import java.awt.event.*;
    import javax.swing.filechooser.*;
    import javax.swing.*;
    import sun.swing.*;
    import javax.swing.plaf.*;
    import java.io.*;
    import javax.swing.filechooser.*;
    import javax.swing.plaf.*;
    import javax.swing.plaf.basic.*;
    import java.lang.reflect.*;
    import java.beans.*;
    public class FileBrowserAttempt2  extends JFrame
         static FilePane Files;
         static JPanel Details;
         static JPanel list;
         static int activeView = 0;
         JFrame f;
        FileBrowserAttempt2 a = this;
        JPopupMenu pop;
        Action[] actions;
        JFileChooser toGetFileView;
         public  FileBrowserAttempt2(final JFileChooser toGetFileView) throws Exception
               try {
             // Set System L&F
            UIManager.setLookAndFeel(
                UIManager.getSystemLookAndFeelClassName());
             } catch(Exception e)
              Files = getFilePane(toGetFileView);               
                   view = Files.getViewMenu();
                   Details = Files.createDetailsView();
                   list = Files.createList();
                   pop = Files.getComponentPopupMenu();
                   actions = Files.getActions();
              pop.remove(view);
              for(Action Comp : actions)
                   System.out.println(Comp.getValue(Comp.NAME).toString());
              Component[] ary = toGetFileView.getComponents();
              setJMenuBar(createMenuBar());
              JPanel panel = new JPanel(new BorderLayout());
              panel.add(ary[0], BorderLayout.NORTH);
              panel.add(Files, BorderLayout.CENTER);     
              add(panel);
              setDefaultCloseOperation(3);
              pack();
              show();
         // THIS IS THE MOUSE LISTENER
         private class open extends  AbstractAction
                   public void actionPerformed(ActionEvent e)
                        try{
                        Class FileBrowser = FileBrowserAttempt2.this.Files.getClass();
                        Method a = FileBrowser.getMethod("getSelectedFile");
                        System.out.println("Action");
                        File open =(File) a.invoke(null);
                        Runtime.getRuntime().exec("cmd.exe start " + open.toString());
                        }catch(Exception ex)
                             ex.printStackTrace();
         public static void main (String[] args) throws Exception
               new FileBrowserAttempt2(new JFileChooser(new File("C:/")));
         public void printAry(Object[] ary)
              for(Object Comp : ary)
                   System.out.println(Comp.toString());
         private FilePane getFilePane(JFileChooser toGetFileView)
              Component[] components = toGetFileView.getComponents();
              for(Object Comp : components)
                   if(Comp instanceof FilePane)
                        return ((FilePane)Comp);
              return null;
         final JMenu view;
        private JMenuBar createMenuBar()
             JMenuBar menuBar = new JMenuBar();
             JMenu FileMen = new JMenu("File");        
             JMenuItem Exit = new JMenuItem("Exit");
             Exit.addActionListener(new ExitListener());
             FileMen.add(Exit);
             menuBar.add(FileMen);
             menuBar.add(view);
             return menuBar;
    class ExitListener implements ActionListener
         public void actionPerformed(ActionEvent e)
                  System.exit(0);
    }and here are the methods of FilePane
    public static final java.lang.String ACTION_APPROVE_SELECTION;
        public static final java.lang.String ACTION_CANCEL;
        public static final java.lang.String ACTION_EDIT_FILE_NAME;
        public static final java.lang.String ACTION_REFRESH;
        public static final java.lang.String ACTION_CHANGE_TO_PARENT_DIRECTORY;
        public static final java.lang.String ACTION_NEW_FOLDER;
        public static final java.lang.String ACTION_VIEW_LIST;
        public static final java.lang.String ACTION_VIEW_DETAILS;
        public static final int VIEWTYPE_LIST;
        public static final int VIEWTYPE_DETAILS;
        int lastIndex;
        java.io.File editFile;
        int editX;
    javax.swing.JTextField editCell;
        protected javax.swing.Action newFolderAction;
        public sun.swing.FilePane(sun.swing.FilePane$FileChooserUIAccessor);
        public void uninstallUI();
        protected javax.swing.JFileChooser getFileChooser();
        protected javax.swing.plaf.basic.BasicDirectoryModel getModel();
        public int getViewType();
        public void setViewType(int);
        public javax.swing.Action getViewTypeAction(int);
        public void setViewPanel(int, javax.swing.JPanel);
        protected void installDefaults();
        public javax.swing.Action[] getActions();
        protected void createActionMap();
        public static void addActionsToMap(javax.swing.ActionMap, javax.swing.Action[]);
        public javax.swing.JPanel createList();
        public javax.swing.JPanel createDetailsView();
        public javax.swing.event.ListSelectionListener createListSelectionListener();
        public javax.swing.Action getNewFolderAction();
        void setFileSelected();
        public void propertyChange(java.beans.PropertyChangeEvent);
        public void ensureFileIsVisible(javax.swing.JFileChooser, java.io.File);
        public void rescanCurrentDirectory();
        public void clearSelection();
        public javax.swing.JMenu getViewMenu();
        public javax.swing.JPopupMenu getComponentPopupMenu();
        protected sun.swing.FilePane$Handler getMouseHandler();
        protected boolean isDirectorySelected();
        protected java.io.File getDirectory();
        public static boolean canWrite(java.io.File);any help would be appreciated

    Its better you create your own panel to display each of the files, than to display the first element of the 'toGetFileView.getComponents()' In this way, you can add a mouse listener to each of those elements.

  • How does the JFileChooser "readOnly" property work?

    The "normal" behaviour for a file chooser usiing the UIManager "FileChooser.readOnly" default value of Boolean.FALSE is:
    1) A "New Folder" button is displayed
    2) When a File in the list is selected you can use the F2 key to rename the file
    3) Or, if you click on an already selected file you will also be able to rename the file
    When you use:
    UIManager.put("FileChooser.readOnly", Boolean.TRUE);then the behaviour changes:
    1) The "New Folder" button is not displayed
    2) You can't rename the file by using F2
    3) You can't rename the file by clicking on a selected file
    I am curious how the "readOnly" property works?
    Looking through the source code of BasicFileChooserUI and MetalFileChooserUI it was easy to see that the "New Folder" button is not created when the "readOnly" property is true.
    However, I can't figure out how "file name editing" works. Using Key Bindings I was able to find the binding between the F2 key and an Action named "editFileName". However, I can't find where this Action is actually created in the UI. I also can't figure out how clicking on a selected file name invokes this Action.
    Does anybody know how to prevent the mouse click from allowing editing of the file name? Does anybody know where the "editFileName" Action is created and how this Action gets invoked by a mouse click?
    This is only a curiosity question. Just when I think I understand Actions and Key Bindings I find something like this that I don't understand.
    The following SSCCE shows:
    1) the normal behaviour of a file chooser
    2) the "readOnly" behaviour of a file chooser
    3) my attempt to simulate the "readOnly" behaviour of a file chooser. It works except a mouse click still allows editing of the file name.
    import java.awt.*;
    import java.beans.*;
    import java.awt.event.*;
    import javax.swing.*;
    public class FileChooserSSCCE extends JPanel
        public FileChooserSSCCE()
            //  Demonstrate default file chooser functionality
            JButton normal = new JButton("Normal");
            normal.addActionListener( new ActionListener()
                public void actionPerformed(ActionEvent e)
                    UIManager.put("FileChooser.readOnly", Boolean.FALSE);
                    JFileChooser fc = new JFileChooser(".");
                    fc.showSaveDialog(null);
            add( normal );
            //  Demonstrate "read only" property
            JButton readOnly = new JButton("Read Only");
            readOnly.addActionListener( new ActionListener()
                public void actionPerformed(ActionEvent e)
                    UIManager.put("FileChooser.readOnly", Boolean.TRUE);
                    JFileChooser fc = new JFileChooser(".");
                    fc.showSaveDialog(null);
            add( readOnly );
            //  Simulate "read only" property
            JButton simulate = new JButton("Simulate Read Only");
            simulate.addActionListener( new ActionListener()
                public void actionPerformed(ActionEvent e)
                    UIManager.put("FileChooser.readOnly", Boolean.FALSE);
                    JFileChooser fc = new JFileChooser(".");
                    ActionMap am = fc.getActionMap();
                    //  Disable the New Folder action. The action gets re-enabled every time
                    //  a new directory is selected so we need the PropertyChangeListener
                    final Action newFolder = am.get("New Folder");
                    newFolder.setEnabled( false );
                    newFolder.addPropertyChangeListener( new PropertyChangeListener()
                       public void propertyChange(PropertyChangeEvent e)
                            newFolder.setEnabled( false );
                    //  The other solution is to remove the button then you don't need to
                    //  disable the action. This solution requires Darryl's SwingUtils
                    //  class: http://tips4java.wordpress.com/2008/11/13/swing-utils/
                    //  Comment the above code and uncomment below if you want to test this.
                    Icon icon = UIManager.getIcon("FileChooser.newFolderIcon");
                    JButton button =
                        SwingUtils.getDescendantOfType(JButton.class, fc, "Icon", icon);
                    button.getParent().remove(button);
                    //  Disable editing of the file name by using F2
                    InputMap im = fc.getInputMap(JFileChooser.WHEN_ANCESTOR_OF_FOCUSED_COMPONENT);
                    im.put(KeyStroke.getKeyStroke("F2"), "none");
                    fc.showSaveDialog(null);
            add( simulate );
        private static void createAndShowUI()
            JFrame frame = new JFrame("FileChooserSSCCE");
            frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
            frame.add( new FileChooserSSCCE() );
            frame.pack();
            frame.setLocationRelativeTo( null );
            frame.setVisible( true );
        public static void main(String[] args)
            EventQueue.invokeLater(new Runnable()
                public void run()
                    createAndShowUI();
    }This question was inspired by by my attemtp to help with this question: http://www.coderanch.com/t/555535/GUI/java/FileChooser-readOnly

    However, I can't figure out how "file name editing" works. Using Key Bindings I was able to find the binding between the F2 key and an Action named "editFileName". However, I can't find where this Action is actually created in the UI. I also can't figure out how clicking on a selected file name invokes this Action.I guess that would be in the proprietary <tt>sun.swing.FilePane</tt> class. EDIT: Also, disabling the <tt>Action</tt> showed that clicking doesn't invoke the <tt>Action</tt>. It's possible that both clicking and the <tt>Action</tt>'s <tt>actionPerformed(...)</tt> invoke the same method, which starts the editing.
    Does anybody know how to prevent the mouse click from allowing editing of the file name?Removing the associated <tt>MouseListener</tt> (in an unacceptably implementation dependent way) seems to do it. The detail view, which is an anonymous <tt>JTable</tt> subclass, is a bigger problem as the API doesn't provide a means to block editing, and removing the <tt>MouseListener</tt> also blocks cell selection events.
    Here's a working example I wouldn't recommend anyone to use in a real-world application. For other members reading this, the <tt>SwingUtils</tt> class is available hereimport darrylbu.util.SwingUtils;
    import java.awt.Container;
    import java.awt.event.*;
    import java.beans.PropertyChangeEvent;
    import java.beans.PropertyChangeListener;
    import javax.swing.*;
    public class ReadOnlyFileChooser {
      public static void main(String[] args) {
        SwingUtilities.invokeLater(new Runnable() {
          @Override
          public void run() {
            new ReadOnlyFileChooser().makeUI();
      public void makeUI() {
        final JFileChooser chooser = new JFileChooser();
        InputMap inputMap = chooser.getInputMap(JFileChooser.WHEN_ANCESTOR_OF_FOCUSED_COMPONENT);
        inputMap.put(KeyStroke.getKeyStroke("F2"), "none");
        final JList list = SwingUtils.getDescendantOfType(JList.class, chooser, "Enabled", true);
        final MouseListener mouseListener = list.getMouseListeners()[2];
        list.removeMouseListener(mouseListener);
        list.addMouseListener(new MouseAdapter() {
          @Override
          public void mouseClicked(MouseEvent e) {
            if (e.getClickCount() == 2) {
              mouseListener.mouseClicked(e);
        final Container filePane = SwingUtilities.getAncestorOfClass(sun.swing.FilePane.class, list);
        filePane.addContainerListener(new ContainerAdapter() {
          @Override
          public void componentAdded(ContainerEvent e) {
            final JTable table = SwingUtils.getDescendantOfType(JTable.class, chooser, "Enabled", true);
            if (table != null && table.getPropertyChangeListeners("tableCellEditor").length == 0) {
              table.addPropertyChangeListener("tableCellEditor", new PropertyChangeListener() {
                @Override
                public void propertyChange(PropertyChangeEvent evt) {
                  SwingUtilities.invokeLater(new Runnable() {
                    @Override
                    public void run() {
                      if (table.isEditing()) {
                        table.getCellEditor().stopCellEditing();
        chooser.showOpenDialog(null);
    }db
    Edited by: Darryl Burke
    Edited(2) by: Darryl Burke -- shortened and improved the code

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

  • Load, crop and saving jpg and gif images with JFileChooser

    Hello!
    I wonder is there someone out there who can help me with a applic that load, (crop) and saving images using JFileChooser with a simple GUI as possible. I'm new to programming and i hope someone can show me.
    Tor

    import java.awt.*;
    import java.awt.event.*;
    import java.awt.image.*;
    import java.io.*;
    import javax.imageio.ImageIO;
    import javax.swing.*;
    import javax.swing.event.*;
    import javax.swing.filechooser.*;
    import javax.swing.filechooser.FileFilter;
    public class ChopShop extends JPanel {
        JFileChooser fileChooser;
        BufferedImage image;
        Rectangle clip = new Rectangle(50,50,150,150);
        boolean showClip = true;
        public ChopShop() {
            fileChooser = new JFileChooser(".");
            fileChooser.setFileFilter(new ImageFilter());
        public void setClip(int x, int y) {
            clip.setLocation(x, y);
            repaint();
        protected void paintComponent(Graphics g) {
            super.paintComponent(g);
            Graphics2D g2 = (Graphics2D)g;
            g2.setRenderingHint(RenderingHints.KEY_ANTIALIASING,
                                RenderingHints.VALUE_ANTIALIAS_ON);
            if(image != null) {
                int x = (getWidth() - image.getWidth())/2;
                int y = (getHeight() - image.getHeight())/2;
                g2.drawImage(image, x, y, this);
            if(showClip) {
                g2.setPaint(Color.red);
                g2.draw(clip);
        public Dimension getPreferredSize() {
            int width = 400;
            int height = 400;
            int margin = 20;
            if(image != null) {
                width = image.getWidth() + 2*margin;
                height = image.getHeight() + 2*margin;
            return new Dimension(width, height);
        private void showOpenDialog() {
            if(fileChooser.showOpenDialog(this) == JFileChooser.APPROVE_OPTION) {
                File file = fileChooser.getSelectedFile();
                try {
                    image = ImageIO.read(file);
                } catch(IOException e) {
                    System.out.println("Read error for " + file.getPath() +
                                       ": " + e.getMessage());
                    image = null;
                revalidate();
                repaint();
        private void showSaveDialog() {
            if(image == null || !showClip)
                return;
            if(fileChooser.showSaveDialog(this) == JFileChooser.APPROVE_OPTION) {
                File file = fileChooser.getSelectedFile();
                String ext = ((ImageFilter)fileChooser.getFileFilter()).getExtension(file);
                // Make sure we have an ImageWriter for this extension.
                if(!canWriteTo(ext)) {
                    System.out.println("Cannot write image to " + ext + " file.");
                    String[] formatNames = ImageIO.getWriterFormatNames();
                    System.out.println("Supported extensions are:");
                    for(int j = 0; j < formatNames.length; j++)
                        System.out.println(formatNames[j]);
                    return;
                // If file exists, warn user, confirm overwrite.
                if(file.exists()) {
                    String message = "<html>" + file.getPath() + " already exists" +
                                     "<br>Do you want to replace it?";
                    int n = JOptionPane.showConfirmDialog(this, message, "Confirm",
                                                          JOptionPane.YES_NO_OPTION);
                    if(n != JOptionPane.YES_OPTION)
                        return;
                // Get the clipped image, if available. This is a subImage
                // of image -> they share the same data. Handle with care.
                BufferedImage clipped = getClippedImage();
                if(clipped == null)
                    return;
                // Copy the clipped image for safety.
                BufferedImage cropped = copy(clipped);
                boolean success = false;
                // Write cropped to the user-selected file.
                try {
                    success = ImageIO.write(cropped, ext, file);
                } catch(IOException e) {
                    System.out.println("Write error for " + file.getPath() +
                                       ": " + e.getMessage());
                System.out.println("writing image to " + file.getPath() +
                                   " was" + (success ? "" : " not") + " successful");
        private boolean canWriteTo(String ext) {
            // Support for writing gif format is new in j2se 1.6
            String[] formatNames = ImageIO.getWriterFormatNames();
            //System.out.printf("writer formats = %s%n",
            //                   java.util.Arrays.toString(formatNames));
            for(int j = 0; j < formatNames.length; j++) {
                if(formatNames[j].equalsIgnoreCase(ext))
                    return true;
            return false;
        private BufferedImage getClippedImage() {
            int w = getWidth();
            int h = getHeight();
            int iw = image.getWidth();
            int ih = image.getHeight();
            // Find origin of centered image.
            int ix = (w - iw)/2;
            int iy = (h - ih)/2;
            // Find clip location relative to image origin.
            int x = clip.x - ix;
            int y = clip.y - iy;
            // clip must be within image bounds to continue.
            if(x < 0 || x + clip.width  > iw || y < 0 || y + clip.height > ih) {
                System.out.println("clip is outside image boundries");
                return null;
            BufferedImage subImage = null;
            try {
                subImage = image.getSubimage(x, y, clip.width, clip.height);
            } catch(RasterFormatException e) {
                System.out.println("RFE: " + e.getMessage());
            // Caution: subImage is not independent from image. Changes
            // to one will affect the other. Copying is recommended.
            return subImage;
        private BufferedImage copy(BufferedImage src) {
            int w = src.getWidth();
            int h = src.getHeight();
            BufferedImage dest = new BufferedImage(w, h, src.getType());
            Graphics2D g2 = dest.createGraphics();
            g2.drawImage(src, 0, 0, this);
            g2.dispose();
            return dest;
        private JPanel getControls() {
            JPanel panel = new JPanel(new GridBagLayout());
            GridBagConstraints gbc = new GridBagConstraints();
            gbc.weightx = 1.0;
            gbc.fill = GridBagConstraints.HORIZONTAL;
            gbc.gridwidth = GridBagConstraints.REMAINDER;
            panel.add(getCropPanel(), gbc);
            panel.add(getImagePanel(), gbc);
            return panel;
        private JPanel getCropPanel() {
            JToggleButton toggle = new JToggleButton("clip", showClip);
            toggle.addActionListener(new ActionListener() {
                public void actionPerformed(ActionEvent e) {
                    showClip = ((AbstractButton)e.getSource()).isSelected();
                    repaint();
            SpinnerNumberModel widthModel = new SpinnerNumberModel(150, 10, 400, 1);
            final JSpinner widthSpinner = new JSpinner(widthModel);
            SpinnerNumberModel heightModel = new SpinnerNumberModel(150, 10, 400, 1);
            final JSpinner heightSpinner = new JSpinner(heightModel);
            ChangeListener cl = new ChangeListener() {
                public void stateChanged(ChangeEvent e) {
                    JSpinner spinner = (JSpinner)e.getSource();
                    int value = ((Number)spinner.getValue()).intValue();
                    if(spinner == widthSpinner)
                        clip.width = value;
                    if(spinner == heightSpinner)
                        clip.height = value;
                    repaint();
            widthSpinner.addChangeListener(cl);
            heightSpinner.addChangeListener(cl);
            JPanel panel = new JPanel(new GridBagLayout());
            GridBagConstraints gbc = new GridBagConstraints();
            gbc.insets = new Insets(2,2,2,2);
            gbc.weightx = 1.0;
            panel.add(toggle, gbc);
            addComponents(new JLabel("width"),  widthSpinner,  panel, gbc);
            addComponents(new JLabel("height"), heightSpinner, panel, gbc);
            return panel;
        private void addComponents(Component c1, Component c2, Container c,
                                   GridBagConstraints gbc) {
            gbc.anchor = GridBagConstraints.EAST;
            c.add(c1, gbc);
            gbc.anchor = GridBagConstraints.WEST;
            c.add(c2, gbc);
        private JPanel getImagePanel() {
            final JButton open = new JButton("open");
            final JButton save = new JButton("save");
            ActionListener al = new ActionListener() {
                public void actionPerformed(ActionEvent e) {
                    JButton button = (JButton)e.getSource();
                    if(button == open)
                        showOpenDialog();
                    if(button == save)
                        showSaveDialog();
            open.addActionListener(al);
            save.addActionListener(al);
            JPanel panel = new JPanel();
            panel.add(open);
            panel.add(save);
            return panel;
        public static void main(String[] args) {
            ChopShop chopShop = new ChopShop();
            ClipMover mover = new ClipMover(chopShop);
            chopShop.addMouseListener(mover);
            chopShop.addMouseMotionListener(mover);
            JFrame f = new JFrame("click inside rectangle to drag");
            f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
            f.getContentPane().add(new JScrollPane(chopShop));
            f.getContentPane().add(chopShop.getControls(), "Last");
            f.pack();
            f.setLocation(200,100);
            f.setVisible(true);
    class ImageFilter extends FileFilter {
        static String GIF = "gif";
        static String JPG = "jpg";
        static String PNG = "png";
        // bmp okay in j2se 1.5+
        public boolean accept(File file) {
            if(file.isDirectory())
                return true;
            String ext = getExtension(file).toLowerCase();
            if(ext.equals(GIF) || ext.equals(JPG) || ext.equals(PNG))
                return true;
            return false;
        public String getDescription() {
            return "gif, jpg, png images";
        public String getExtension(File file) {
            String s = file.getPath();
            int dot = s.lastIndexOf(".");
            return (dot != -1) ? s.substring(dot+1) : "";
    class ClipMover extends MouseInputAdapter {
        ChopShop component;
        Point offset = new Point();
        boolean dragging = false;
        public ClipMover(ChopShop cs) {
            component = cs;
        public void mousePressed(MouseEvent e) {
            Point p = e.getPoint();
            if(component.clip.contains(p)) {
                offset.x = p.x - component.clip.x;
                offset.y = p.y - component.clip.y;
                dragging = true;
        public void mouseReleased(MouseEvent e) {
            dragging = false;
        public void mouseDragged(MouseEvent e) {
            if(dragging) {
                int x = e.getX() - offset.x;
                int y = e.getY() - offset.y;
                component.setClip(x, y);
    }

  • 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 detecting switch between "List" and "Details" views

    I'm customizing a JFileChooser and would like to provide users a longer version of the file names when in Details mode (Unix showing links).
    This might be accomplished using the getDescription method of FileView, I don't know. My FileView getTypeDescription and getDescription methods are never called but getIcon is. I added @Override annotations to all method, so I think I really am overriding them.
    Thanks!

    Here's a solution. I still think there should be a more official way of doing this.
    public MyFileView(JFileChooser chooser)
              for ( Component c : chooser.getComponents())
                   if (c.getClass() == FilePane.class)
                        filePane = (FilePane) c;
         @Override
         public String getName(File f)
              if (filePane.getViewType() == FilePane.VIEWTYPE_DETAILS){
                   return "Long";
              return null;
         }

  • JFileChooser - List and Details

    Hi,
    In the JFileChooser Dialog, we have two buttons "List" and "Details" to view and select the files.
    The default is "List" mode, when the File Chooser dialog opens.
    In this mode, if we type in the first character of the file we want to select, then the FileChooser will automatically focus the first file in that directory starting with that letter.
    For Example: If I type in 's' in the "File Name" text filed, the focus is on the first file in that directory starting with letter 's' like "sample.txt".
    But this same feature is not available in the "Details" mode.
    Does anyone have an idea of how to incorporate this in the "Details" mode ?
    Also is there a way to make the "Details" mode as the default mode when the FileChooser dialog opens.
    I have tried many sources but could not find any information regarding this problem.
    Any help will be appreciated.
    Thanks in advance,
    Neeharika.

    Here's a solution. I still think there should be a more official way of doing this.
    public MyFileView(JFileChooser chooser)
              for ( Component c : chooser.getComponents())
                   if (c.getClass() == FilePane.class)
                        filePane = (FilePane) c;
         @Override
         public String getName(File f)
              if (filePane.getViewType() == FilePane.VIEWTYPE_DETAILS){
                   return "Long";
              return null;
         }

  • JFileChooser "List" and "Details" button disabled.

    Hi,
    The two buttons "List" and "Details" buttons on the top-right of my JFileChooser dialog box are both disabled.
    Dose anyone know how to enable them?
    Thanks
    slam

    Here's a solution. I still think there should be a more official way of doing this.
    public MyFileView(JFileChooser chooser)
              for ( Component c : chooser.getComponents())
                   if (c.getClass() == FilePane.class)
                        filePane = (FilePane) c;
         @Override
         public String getName(File f)
              if (filePane.getViewType() == FilePane.VIEWTYPE_DETAILS){
                   return "Long";
              return null;
         }

  • JFileChooser functioning like normal Windows Apps FileChooser

    I have this problem that's been giving me too much headache already. When you click on Open on any Windows app, and click on the "Details" button, it will show you the files' details (FileName, Type, Date, etc.). This is the same with JFileChooser, so no problem there. The thing is, with Windows apps, you can click on the headers and have the files sorted according to the header you clicked. This doesn't happen to a JFileChooser. Has any of you guys did this or found any solution to this problem? I've searched (almost) everywhere, Google, Sun, etc., I even looked into JFileChooser's source code but I can't seem to find anything.
    I know this is possible, so anyone who can help, you'll be greatly appreciated.

    Thought I would pass along some updated code for this as this was very helpful to us as we are still on jdk 1.5.
    This has been modified to use the Windows UI. The advantage of doing this in the UI class is so you can set it as the default UI for JFileChooser inside your application. If you had this as a subclass of JFileChooser (as it is above) then you explicitly have to use that subclass throughout your application. By setting this UI class as the FileChooserUI in your UIDefaults table then every instance of JFileChooser will now automatically use your overridden UI and theres nothing else you have to do.
    import java.awt.Component;
    import java.awt.Container;
    import java.awt.event.MouseAdapter;
    import java.awt.event.MouseEvent;
    import java.io.File;
    import java.util.Collections;
    import java.util.Comparator;
    import java.util.Vector;
    import javax.swing.JComponent;
    import javax.swing.JFileChooser;
    import javax.swing.JPanel;
    import javax.swing.JTable;
    import javax.swing.UIManager;
    import javax.swing.plaf.ComponentUI;
    import javax.swing.plaf.basic.BasicDirectoryModel;
    import javax.swing.table.JTableHeader;
    import javax.swing.table.TableColumn;
    import javax.swing.table.TableColumnModel;
    import com.sun.java.swing.plaf.windows.WindowsFileChooserUI;
    public class SortableFileChooserUI extends WindowsFileChooserUI {
         private DirectoryModel model;
         public static ComponentUI createUI(JComponent c) {
              return new SortableFileChooserUI((JFileChooser)c);
         public SortableFileChooserUI(JFileChooser filechooser) {
              super(filechooser);
         @Override
      protected final void createModel() {
              this.model = new DirectoryModel(getFileChooser());
          * Overridden to get our own model
          * @return
         @Override
      public final BasicDirectoryModel getModel() {
              return this.model;
          * Calls the default method then adds a MouseListener to the JTable
          * @param chooser
          * @return
         @Override
      protected final JPanel createDetailsView(JFileChooser chooser) {
              JPanel panel = super.createDetailsView(chooser);
              //Since we can't access FileChooserUI's private member detailsTable
              //directly, we have to find it in the JPanel
              final JTable tbl = findJTable(panel.getComponents());
              if (tbl != null) {
                   //Fix the columns so they can't be rearranged, if we don't do this
                   //we would need to keep track when each column is moved
                   tbl.getTableHeader().setReorderingAllowed(false);
                   //Add a mouselistener to listen for clicks on column headers
                   tbl.getTableHeader().addMouseListener(new MouseAdapter() {
                        @Override
            public void mouseClicked(MouseEvent e) {
                             //Only process single clicks
                             if (e.getClickCount() > 1) {
                return;
                             e.consume();
                             Column column = Column.getColumn(tbl.getTableHeader().columnAtPoint(e.getPoint()));
                             if ((column != null) && column.isSortable()) {
                SortableFileChooserUI.this.model.sort(tbl.getTableHeader().columnAtPoint(e.getPoint()), tbl);
              return panel;
          * Finds the JTable in the panel so we can add MouseListener
          * @param comp
          * @return
         private final JTable findJTable(Component[] comp) {
              for (int i = 0; i < comp.length; i++) {
                   if (comp[i] instanceof JTable) {
                        return (JTable)comp;
                   if (comp[i] instanceof Container) {
                        JTable tbl = findJTable(((Container)comp[i]).getComponents());
                        if (tbl != null) {
    return tbl;
              return null;
         private final static class DirectoryModel extends BasicDirectoryModel {
              private Column col = Column.FILENAME;
              private boolean ascending;
              private Comparator<File> filesizeComparator = new FilesizeComparator();
              private Comparator<File> filenameComparator = new FilenameComparator();
              private Comparator<File> filedateComparator = new FiledateComparator();
              * Must be overridden to extend BasicDirectoryModel
              * @param chooser
              protected DirectoryModel(JFileChooser chooser) {
                   super(chooser);
              * Resorts the JFileChooser table based on new column
              * @param c
              protected final void sort(int c, JTable tbl) {
                   //Set column and order
                   this.col = Column.getColumn(c);
                   this.ascending = !this.ascending;
                   String indicator = " ^";
                   if (this.ascending) {
                        indicator = " v";
                   final JTableHeader th = tbl.getTableHeader();
                   final TableColumnModel tcm = th.getColumnModel();
                   for (Column column : Column.values()) {
                        tcm.getColumn(column.getIndex()).setHeaderValue(column.getLabel());
                   final TableColumn tc = tcm.getColumn(this.col.getIndex()); // the column to change
                   tc.setHeaderValue(this.col.getLabel() + indicator);
                   th.repaint();
                   //Requery the file listing
                   validateFileCache();
              * Sorts the data based on current column setting
              * @param data
              @Override
    protected final void sort(Vector<? extends File> data) {
                   Comparator<File> comparator = null;
                   switch (this.col) {
                        case FILEDATE:
                             comparator = this.filedateComparator;
                             break;
                        case FILESIZE:
                             comparator = this.filesizeComparator;
                             break;
                        case FILENAME:
                             comparator = this.filenameComparator;
                             break;
                        default:
                             comparator = null;
                             break;
                   if (comparator != null) {
                        Collections.sort(data, comparator);
              private class FiledateComparator implements Comparator<File> {
                   public int compare(File a, File b) {
                        int ret = 1;
                        if (a.lastModified() > b.lastModified()) {
                             ret = -1;
                        else if (a.lastModified() == b.lastModified()) {
                             ret = 0;
                        if (DirectoryModel.this.ascending) {
                             ret *= -1;
                        return ret;
              private class FilesizeComparator implements Comparator<File> {
                   public int compare(File a, File b) {
                        int ret = 1;
                        if (a.length() > b.length()) {
                             ret = -1;
                        else if (a.length() == b.length()) {
                             ret = 0;
                        if (DirectoryModel.this.ascending) {
                             ret *= -1;
                        return ret;
              private class FilenameComparator implements Comparator<File> {
                   public int compare(File a, File b) {
                        if (DirectoryModel.this.ascending) {
                             return a.getName().compareToIgnoreCase(b.getName());
                        else {
                             return -1 * a.getName().compareToIgnoreCase(b.getName());
         private enum Column {
              FILENAME(0, UIManager.getString("FileChooser.fileNameHeaderText"), true),
              FILESIZE(1, UIManager.getString("FileChooser.fileSizeHeaderText"), true),
              FILETYPE(2, UIManager.getString("FileChooser.fileTypeHeaderText")),
              FILEDATE(3, UIManager.getString("FileChooser.fileDateHeaderText"), true),
              FILEATTR(4, UIManager.getString("FileChooser.fileAttrHeaderText"));
              private int index;
              private String label;
              private boolean isSortable;
              private Column(int index, String label) {
                   this(index, label, false);
              private Column(int index, String label, boolean isSortable) {
                   this.index = index;
                   this.label = label;
                   this.isSortable = isSortable;
              protected int getIndex() { return this.index; }
              protected String getLabel() { return this.label; }
              protected boolean isSortable() { return this.isSortable; }
              @Override public String toString() { return getLabel(); }
              protected static Column getColumn(int index) {
                   for (Column column : values()) {
                        if (column.getIndex() == index) {
                             return column;
                   return null;

  • JFileChooser's approve button text changes when file

    I have a JFileChooser used for loading some XML file(s). We want the approve button's text to be "Load". When I bring up the dialog, the button text initially reads "Load", when I select a directory, it reads "Open", if I select a file again, it goes back to "Load". So far, so good.
    The problem comes when using it in a non-English language. When I bring up the dialog, the button text initially reads the appropriately translated "Load". However, when I select a directory, it changes to the English "Open". I do not see a method to use to adjust this text. Am I missing something, or is this a bug?
    Any help is greatly appreciated.
    Jamie

    Here's some code I'll put into the public domain:
    package com.graphbuilder.desktop;
    import java.awt.*;
    import java.awt.event.*;
    import javax.swing.*;
    import java.util.Stack;
    import java.util.Vector;
    import java.util.StringTokenizer;
    import java.io.File;
    <p>Attempt to improve the behaviour of the JFileChooser.  Anyone who has used the
    the JFileChooser will probably remember that it lacks several useful features.
    The following features have been added:
    <ul>
    <li>Double click to choose a file</li>
    <li>Enter key to choose a file after typing the filename</li>
    <li>Enter key to change to a different directory after typing the filename</li>
    <li>Automatic rescanning of directories</li>
    <li>A getSelectedFiles method that returns the correct selected files</li>
    <li>Escape key cancels the dialog</li>
    <li>Access to common GUI components, such as the OK and Cancel buttons</li>
    <li>Removal of the useless Update and Help buttons in Motif L&F</li>
    </ul>
    <p>There are a lot more features that could be added to make the JFileChooser more
    user friendly.  For example, a drop-down combo-box as the user is typing the name of
    the file, a list of currently visited directories, user specified file filtering, etc.
    <p>The look and feels supported are Metal, Window and Motif.  Each look and feel
    puts the OK and Cancel buttons in different locations and unfortunately the JFileChooser
    doesn't provide direct access to them.  Thus, for each look-and-feel the buttons must
    be found.
    <p>The following are known issues:  Rescanning doesn't work when in Motif L&F.  Some
    L&Fs have components that don't become available until the user clicks a button.  For
    example, the Metal L&F has a JTable but only when viewing in details mode.  The double
    click to choose a file does not work in details mode.  There are probably more unknown
    issues, but the changes made so far should make the JFileChooser easier to use.
    public class FileChooserFixer implements ActionListener, KeyListener, MouseListener, Runnable {
         Had to make new buttons because when the original buttons are clicked
         they revert back to the original label text.  I.e. some programmer decided
         it would be a good idea to set the button text during an actionPerformed
         method.
         private JFileChooser fileChooser = null;
         private JButton okButton = new JButton("OK");
         private JButton cancelButton = new JButton("Cancel");
         private JList fileList = null;
         private JTextField filenameTextField = null;
         private ActionListener actionListener = null;
         private long rescanTime = 20000;
         public FileChooserFixer(JFileChooser fc, ActionListener a) {
              fileChooser = fc;
              actionListener = a;
              fileChooser.setFileSelectionMode(JFileChooser.DIRECTORIES_ONLY);
              okButton.setMnemonic('O');
              cancelButton.setMnemonic('C');
              JButton oldOKButton = null;
              JButton oldCancelButton = null;
              JTextField[] textField = getTextFields(fc);
              JButton[] button = getButtons(fc);
              JList[] list = getLists(fc);
              String laf = javax.swing.UIManager.getLookAndFeel().getClass().getName();
              if (laf.equals("javax.swing.plaf.metal.MetalLookAndFeel")) {
                   oldOKButton = button[0];
                   oldCancelButton = button[1];
                   filenameTextField = textField[0];
                   fileList = list[0];
              else if (laf.equals("com.sun.java.swing.plaf.windows.WindowsLookAndFeel")) {
                   oldOKButton = button[0];
                   oldCancelButton = button[1];
                   filenameTextField = textField[0];
                   fileList = list[0];
              else if (laf.equals("com.sun.java.swing.plaf.motif.MotifLookAndFeel")) {
                   oldOKButton = button[0];
                   oldCancelButton = button[2];
                   button[1].setVisible(false); // hides the do-nothing 'Update' button
                   button[3].setVisible(false); // hides the disabled 'Help' button
                   filenameTextField = textField[1];
                   fileList = list[0];
              fix(oldOKButton, okButton);
              fix(oldCancelButton, cancelButton);
              okButton.addActionListener(this);
              cancelButton.addActionListener(this);
              fileList.addMouseListener(this);
              addKeyListeners(fileChooser);
              new Thread(this).start(); // note: rescanning in Motif feel doesn't work
         public void run() {
              try {
                   while (true) {
                        Thread.sleep(rescanTime);
                        Window w = SwingUtilities.windowForComponent(fileChooser);
                        if (w != null && w.isVisible())
                             fileChooser.rescanCurrentDirectory();
              } catch (Throwable err) {}
         public long getRescanTime() {
              return rescanTime;
         public void setRescanTime(long t) {
              if (t < 200)
                   throw new IllegalArgumentException("Rescan time >= 200 required.");
              rescanTime = t;
         private void addKeyListeners(Container c) {
              for (int i = 0; i < c.getComponentCount(); i++) {
                   Component d = c.getComponent(i);
                   if (d instanceof Container)
                        addKeyListeners((Container) d);
                   d.addKeyListener(this);
         private static void fix(JButton oldButton, JButton newButton) {
              int index = getIndex(oldButton);
              Container c = oldButton.getParent();
              c.remove(index);
              c.add(newButton, index);
              newButton.setPreferredSize(oldButton.getPreferredSize());
              newButton.setMinimumSize(oldButton.getMinimumSize());
              newButton.setMaximumSize(oldButton.getMaximumSize());
         private static int getIndex(Component c) {
              Container p = c.getParent();
              for (int i = 0; i < p.getComponentCount(); i++) {
                   if (p.getComponent(i) == c)
                        return i;
              return -1;
         public JButton getOKButton() {
              return okButton;
         public JButton getCancelButton() {
              return cancelButton;
         public JList getFileList() {
              return fileList;
         public JTextField getFilenameTextField() {
              return     filenameTextField;
         public JFileChooser getFileChooser() {
              return fileChooser;
         protected JButton[] getButtons(JFileChooser fc) {
              Vector v = new Vector();
              Stack s = new Stack();
              s.push(fc);
              while (!s.isEmpty()) {
                   Component c = (Component) s.pop();
                   if (c instanceof Container) {
                        Container d = (Container) c;
                        for (int i = 0; i < d.getComponentCount(); i++) {
                             if (d.getComponent(i) instanceof JButton)
                                  v.add(d.getComponent(i));
                             else
                                  s.push(d.getComponent(i));
              JButton[] arr = new JButton[v.size()];
              for (int i = 0; i < arr.length; i++)
                   arr[i] = (JButton) v.get(i);
              return arr;
         protected JTextField[] getTextFields(JFileChooser fc) {
              Vector v = new Vector();
              Stack s = new Stack();
              s.push(fc);
              while (!s.isEmpty()) {
                   Component c = (Component) s.pop();
                   if (c instanceof Container) {
                        Container d = (Container) c;
                        for (int i = 0; i < d.getComponentCount(); i++) {
                             if (d.getComponent(i) instanceof JTextField)
                                  v.add(d.getComponent(i));
                             else
                                  s.push(d.getComponent(i));
              JTextField[] arr = new JTextField[v.size()];
              for (int i = 0; i < arr.length; i++)
                   arr[i] = (JTextField) v.get(i);
              return arr;
         protected JList[] getLists(JFileChooser fc) {
              Vector v = new Vector();
              Stack s = new Stack();
              s.push(fc);
              while (!s.isEmpty()) {
                   Component c = (Component) s.pop();
                   if (c instanceof Container) {
                        Container d = (Container) c;
                        for (int i = 0; i < d.getComponentCount(); i++) {
                             if (d.getComponent(i) instanceof JList)
                                  v.add(d.getComponent(i));
                             else
                                  s.push(d.getComponent(i));
              JList[] arr = new JList[v.size()];
              for (int i = 0; i < arr.length; i++)
                   arr[i] = (JList) v.get(i);
              return arr;
         public File[] getSelectedFiles() {
              File[] f = fileChooser.getSelectedFiles();
              if (f.length == 0) {
                   File file = fileChooser.getSelectedFile();
                   if (file != null)
                        f = new File[] { file };
              return f;
         public void mousePressed(MouseEvent evt) {
              Object src = evt.getSource();
              if (src == fileList) {
                   if (evt.getModifiers() != InputEvent.BUTTON1_MASK) return;
                   int index = fileList.locationToIndex(evt.getPoint());
                   if (index < 0) return;
                   fileList.setSelectedIndex(index);
                   File[] arr = getSelectedFiles();
                   if (evt.getClickCount() == 2 && arr.length == 1 && arr[0].isFile())
                        actionPerformed(new ActionEvent(okButton, 0, okButton.getActionCommand()));
         public void mouseReleased(MouseEvent evt) {}
         public void mouseClicked(MouseEvent evt) {}
         public void mouseEntered(MouseEvent evt) {}
         public void mouseExited(MouseEvent evt) {}
         public void keyPressed(KeyEvent evt) {
              Object src = evt.getSource();
              int code = evt.getKeyCode();
              if (code == KeyEvent.VK_ESCAPE)
                   actionPerformed(new ActionEvent(cancelButton, 0, cancelButton.getActionCommand()));
              if (src == filenameTextField) {
                   if (code != KeyEvent.VK_ENTER) return;
                   fileList.getSelectionModel().clearSelection();
                   actionPerformed(new ActionEvent(okButton, 0, "enter"));
         public void keyReleased(KeyEvent evt) {}
         public void keyTyped(KeyEvent evt) {}
         public void actionPerformed(ActionEvent evt) {
              Object src = evt.getSource();
              if (src == cancelButton) {
                   if (actionListener != null)
                        actionListener.actionPerformed(evt);
              else if (src == okButton) {
                   File[] selectedFiles = getSelectedFiles();
                   Object obj = fileList.getSelectedValue(); // is null when no file is selected in the JList
                   String text = filenameTextField.getText().trim();
                   if (text.length() > 0 && (obj == null || selectedFiles.length == 0)) {
                        File d = fileChooser.getCurrentDirectory();
                        Vector vec = new Vector();
                        StringTokenizer st = new StringTokenizer(text, "\"");
                        while (st.hasMoreTokens()) {
                             String s = st.nextToken().trim();
                             if (s.length() == 0) continue;
                             File a = new File(s);
                             if (a.isAbsolute())
                                  vec.add(a);
                             else
                                  vec.add(new File(d, s));
                        File[] arr = new File[vec.size()];
                        for (int i = 0; i < arr.length; i++)
                             arr[i] = (File) vec.get(i);
                        selectedFiles = arr;
                   if (selectedFiles.length == 0) {
                        Toolkit.getDefaultToolkit().beep();
                        return;
                   if (selectedFiles.length == 1) {
                        File f = selectedFiles[0];
                        if (f.exists() && f.isDirectory() && text.length() > 0 && evt.getActionCommand().equals("enter")) {
                             fileChooser.setCurrentDirectory(f);
                             filenameTextField.setText("");
                             filenameTextField.requestFocus();
                             return;
                   boolean filesOnly = (fileChooser.getFileSelectionMode() == JFileChooser.FILES_ONLY);
                   boolean dirsOnly = (fileChooser.getFileSelectionMode() == JFileChooser.DIRECTORIES_ONLY);
                   if (filesOnly || dirsOnly) {
                        for (int i = 0; i < selectedFiles.length; i++) {
                             File f = selectedFiles;
                             if (filesOnly && f.isDirectory() || dirsOnly && f.isFile()) {
                                  Toolkit.getDefaultToolkit().beep();
                                  return;
                   fileChooser.setSelectedFiles(selectedFiles);
                   if (actionListener != null)
                        actionListener.actionPerformed(evt);

  • Transparent JFileChooser

    Hi!
    I have yet another "how can I make this thing transparent" question, this time for the JFileChooser. I've written a function to recursively iterate through its components and these are the ones I can find:
    class javax.swing.JPanel
    class javax.swing.JPanel
    class javax.swing.JButton
    class javax.swing.Box$Filler
    class javax.swing.JButton
    class javax.swing.Box$Filler
    class javax.swing.JButton
    class javax.swing.Box$Filler
    class javax.swing.JToggleButton
    class javax.swing.JToggleButton
    class javax.swing.JLabel
    class javax.swing.plaf.metal.MetalFileChooserUI$1
    class javax.swing.JPanel
    class sun.swing.FilePane
    class javax.swing.JPanel
    class javax.swing.JPanel
    class javax.swing.plaf.metal.MetalFileChooserUI$AlignedLabel
    class javax.swing.plaf.metal.MetalFileChooserUI$3
    class javax.swing.Box$Filler
    class javax.swing.JPanel
    class javax.swing.plaf.metal.MetalFileChooserUI$AlignedLabel
    class javax.swing.JComboBox
    class javax.swing.JPanel
    class javax.swing.JButton
    class javax.swing.JButtonRunning setOpaque(false) on all instances of JComponent makes everything but the list of files transparent. From what I can see it's some kind of JList but it doesn't appear in the list above. Is there a way to make this last part transparent as well? Can I somehow run setOpaque(false) on it too?

    Thanks for your replies!
    I realise now I probably should have put some more effort into this before posting. I've created an example that'll hopefully make things clearer.
    Maxideon: You're right, ComboBox doesn't become transparent, it did in my code because I'd set a custom ComboBoxUI.
    It's only the list of files I'm interested in making transparent right now, I've managed to get all of the other components transparent already. Here's the code:
    FileChooserTest.java:
    import java.awt.*;
    import javax.swing.*;
    public class FileChooserTest extends JFrame {
      String background = "bkg.jpg";
      public FileChooserTest() {
        ImageIcon imageIcon = new ImageIcon(background);
        setSize(imageIcon.getIconWidth(), imageIcon.getIconHeight());
        JPanel panel = new JPanel() {
          public void paintComponent(Graphics g) {
            g.drawImage(new ImageIcon(background).getImage(), 0, 0, null);
        panel.setBounds(0, 0, imageIcon.getIconWidth(), imageIcon.getIconHeight());
        UIManager.put("FileChooserUI", MyFileChooserUI.class.getName());
        panel.add(new JFileChooser());
        getContentPane().add(panel);
      public static void main(String[] args) {
        new FileChooserTest().setVisible(true);
    }MyFileChooserUI.java
    import java.awt.*;
    import javax.swing.*;
    import javax.swing.plaf.ComponentUI;
    import javax.swing.plaf.metal.MetalFileChooserUI;
    public class MyFileChooserUI extends MetalFileChooserUI {
      public static ComponentUI createUI(JComponent c) {
        return new MyFileChooserUI((JFileChooser) c);
      private MyFileChooserUI(JFileChooser c) {
        super(c);
      public void installComponents(JFileChooser fc) {
        super.installComponents(fc);
        customize(fc);
      /* Set opacity, call recursively */
      private void customize(Container c) {
        int len = c.getComponentCount();
        for(int i = 0; i < len; i++) {
          Component comp = c.getComponent(i);
          if(comp instanceof JComponent) {
            ((JComponent)comp).setOpaque(false);
          if(comp instanceof Container) {
            customize((Container) comp);
    }thomas.behr: Does your solution work for a JFileChooser added to a JPanel or only when it's a separate Window?
    Is there a way to create a custom ListUI that'll make the list in the JFileChooser transparent?
    Once again, thanks guys and sorry for not creating an example from the start.

  • JFileChooser hangs sometimes

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

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

  • Disabling "rename" on JFileChooser

    Hi,
    I have to disable the rename option on JFileChooser. I understand that I'll have to extend the MetalFileChooserUI class and override the inner class definition of SingleClickListener in order to achieve this. I did exactly the same. But the result was not convincing. First of all the display went wrong. Only the names were displayed, the icons disappeared. Then when I clicked on the file names, it threw up NullPointerExceptions. Can anyone suggest the correct way to do it ?? Thanx.
    Regards,
    Guru

    I have removed the default constructor now. But it still gives me errors while compiling. I'm posting the code and the error down below. I am not able to understand the error.
    import javax.swing.*;
    import java.awt.*;
    import java.awt.event.*;
    import javax.swing.plaf.metal.MetalFileChooserUI;
    import javax.swing.plaf.ComponentUI;
    class clFileChooserMain
         public static void main(String args[])
              JFrame a_oMainFrame = new JFrame();
              clCustomFileChooser a_oChooser = new clCustomFileChooser();
              a_oMainFrame.getContentPane().add(a_oChooser);
              a_oMainFrame.setSize(400,400);
              a_oMainFrame.setVisible(true);
    class clCustomFileChooser extends JFileChooser
         clCustomFileChooser()
              super();
              MyFileChooserUI a_oMetalUI =
                   new MyFileChooserUI(this);
              setUI(a_oMetalUI);
    class MyFileChooserUI extends MetalFileChooserUI
         protected JPanel createList(JFileChooser fc)
              JPanel p = new JPanel(new BorderLayout());
              JList list = new JList();
              list.setCellRenderer(new FileRenderer());
              if (fc.isMultiSelectionEnabled())
                   list.setSelectionMode(ListSelectionModel.MULTIPLE_INTERVAL_SELECTION);
              else
                   list.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
              list.setModel(getModel());
              list.addListSelectionListener(createListSelectionListener(fc));
              list.addMouseListener(createDoubleClickListener(fc, list));
              JScrollPane scrollpane = new JScrollPane(list);
              p.add(scrollpane, BorderLayout.CENTER);
              return p;
    --------------------------- Compiler Output ---------------------------
    clFileChooserMain.java:28: Wrong number of arguments in constructor.
                   new MyFileChooserUI(this);
                   ^
    clFileChooserMain.java:48: No constructor matching MetalFileChooserUI() found in class javax.swing.plaf.metal.MetalFileChooserUI.
    class MyFileChooserUI extends MetalFileChooserUI
          ^
    clFileChooserMain.java:54: No constructor matching MetalFileChooserUI. FileRenderer(MyFileChooserUI) found in inner class javax.swing.plaf.metal.MetalFileChooserUI. FileRenderer.
              list.setCellRenderer(new FileRenderer());
                                   ^
    3 errors

  • Get directory in JFileChooser

    I'm working on a program that should send a file. I want the filename (i have fixed that) and the directory that the file is in.
    How?
    Here is a part of my code:
    import java.io.*;
    import javax.swing.*;
    import java.awt.event.*;
    import java.lang.reflect.Array;
    public class myFileChooser extends JFrame{
         JFileChooser chooser;
         JPanel mainPanel;
         JButton addButton;
         public myFileChooser(){
              chooser = new JFileChooser();
              chooser.setFileSelectionMode(2);
              chooser.setMultiSelectionEnabled(false);
              chooser.setControlButtonsAreShown(true);
              addButton = new JButton("Add");
              addButton.addMouseListener(new command_listner());
              mainPanel = new JPanel();
              mainPanel.add(chooser);
              mainPanel.add(addButton);
              getContentPane().add(mainPanel);
              pack();
              setSize(765,690);
              setVisible(true);
         public class command_listner extends MouseAdapter {
              public void mouseClicked (java.awt.event.MouseEvent evt) {
                   Object source = evt.getSource();
                   if (source == addButton) {
                        String strFileName = chooser.getSelectedFile().getName();
                        System.out.print(strFileName);
         public static void main(String[] args){
              myFileChooser mfc = new myFileChooser();
    }Thanks in advance.

    I'm working on a program that should send a file. I
    want the filename (i have fixed that) and the
    directory that the file is in.
    How?
    File has some intresting methods. Maybe it will have one that returns the parent?

Maybe you are looking for

  • Connect ipad to apple tv

    I want to simply connect my Ipad to my apple tv. How do I do it?

  • Create signature impossible when list is full - bug?

    in Logic 8, creating a signature in the list is easy. but as soon as the list is full, and you get a scroll bar, creating signatures is no longer possible instead, the measure you are in gets 1 quarterlonger each time you press create signature anyon

  • Why can't I sync my calender from iPhone to Gmail ?

    It had worked a long time but this week. I don't change any setting in my iPhone. I tried to enable/disable the canlender of Exchange/iCloud/Gmail, it steal doesn't work. Please help me ! Thanks !

  • Can iPad be affected by viruses on the internet  ?

    Can iPad be affected by viruses on the internet  ?

  • Number (0-100) to String

    I could not find the thread, but remember about a week ago that someone had asked about turning a given number in the range 0-100 into its string equivalent. Here's a little class that does it. Hope it helps... package     public class NumberToText