Mike's face
Wednesday, December 13th, 2017








JFileChooser: prevent renaming through mouse clicks

Tuesday March 29, 2005 17:48

You've seen it a million times, so annoying.  You try to use the JFileChooser to get to a certain directory, and half the time you click to slowly, putting the filename in edit mode, which can be very annoying.  I've put together a hack that'll strip this 'renaming feature' out of the JFileChooser.

Although it is backwards compatible in terms of compilability, it'll only do anything on Java 1.5.

Instead of instantiating JFileChooser, instantiate this deriving class:

public class MyFileChooser extends JFileChooser
{
  public MyFileChooser()
  {
    JList list = findFileList(this);

    for (MouseListener l : list.getMouseListeners())
    {
      if (l.getClass().getName().indexOf("FilePane") >= 0)
      {
        list.removeMouseListener(l);
        list.addMouseListener(new MyMouseListener(l));
      }
    }
  }

  private JList findFileList(Component comp)
  {
    if (comp instanceof JList)
      return (JList)comp;

    if (comp instanceof Container)
    {
      for (Component child : ((Container)comp).getComponents())
      {
        JList list = findFileList(child);
        if (list != null)
          return list;
      }
    }

    return null;
  }

  private class MyMouseListener extends MouseAdapter
  {
    MyMouseListener(MouseListener listenerChain)
    {
      m_listenerChain = listenerChain;
    }
    public void mouseClicked(MouseEvent event)
    {
      if (event.getClickCount() > 1)
        m_listenerChain.mouseClicked(event);
    }
    private MouseListener m_listenerChain;
  }
}

(C) Copyright 2004-2007 Mike Pot