views:

662

answers:

1

Hello

How do I change the JFileChooser behavior from double-click selection to single-click selection mode?

I'm developing an application to run with either a single-click interface (nothing requires a double-click, just like the KDE interface mode) or a double-click interface (the default Windows interface mode or the regular GNOME interface mode). I want the Java application to behave just like the rest of the system to respect the user current configuration and environment.

Thanks, Luis

A: 

The ideal solution should be to set up a configuration value somewhere in the JFileChooser class to have it work either under single-click ordouble-click mode.

Since it seems there is no such a configuration, here is an approximate solution based on Richie_W's idea. I had to extend it a bit in order to allow the user to navigate in many directories and also to avoid reentrant events that get fired when setting the selection. However, as Oscar pointed out, it is not possible to navigate using the keyboard (it always chooses whatever is under focus). If you don't use the keyboard, it works.

JFileChooser _fileChooser=new JFileChooser();

if (ConfigurationManager.isSingleClickDesired()) {
    //We will be interested in files only, but we need to allow it to choose both
    _fileChooser.setFileSelectionMode(JFileChooser.FILES_AND_DIRECTORIES);
    _fileChooser.addPropertyChangeListener(new PropertyChangeListener() {

      //To prevent reentry
  private boolean handlingEvent=false;

      public void propertyChange(PropertyChangeEvent e) {

        //Prevent reentry
        if (handlingEvent)
          return;
        else
          //Mark it as handling the event
          handlingEvent=true;

        String propertyName = e.getPropertyName();

        //We are interested in both event types
        if(propertyName.equals(JFileChooser.SELECTED_FILE_CHANGED_PROPERTY) ||
           propertyName.equals(JFileChooser.DIRECTORY_CHANGED_PROPERTY)){

        File selectedFile = (File) e.getNewValue();
        if (selectedFile!=null) {
          if (selectedFile.isDirectory()) {
            //Allow the user to navigate directories with single click
     _fileChooser.setCurrentDirectory(selectedFile);
          } else {
            _fileChooser.setSelectedFile(selectedFile);
            if (_fileChooser.getSelectedFile()!=null)
          //Accept it
       _fileChooser.approveSelection();
     } 
          } 
        }

 //Allow new events to be processed now
     handlingEvent=false;
    }
  }); 
}

Ps->Sorry for not great looking code format, but StackoverFlow has broken Firefox and Iceweasel code format support under KDE and Gnome.

Luis Soeiro
Ok, after playing more with the code above I noticed that the behavior is different from Konqueror or KDE's file chooser when in single-click mode. :-(
Luis Soeiro