2

如何将JFileChooser行为从双击选择更改为单击选择模式?

我正在开发一个应用程序来运行单击界面(不需要双击,就像 KDE 界面模式)或双击界面(默认的 Windows 界面模式或常规 GNOME 界面模式)。我希望 Java 应用程序的行为与系统的其余部分一样,以尊重用户当前的配置和环境。

4

1 回答 1

-1

理想的解决方案应该是在 JFileChooser 类的某处设置一个配置值,让它在单击或双击模式下工作。

由于貌似没有这样的配置,这里根据Richie_W的思路给出一个大概的解决方案。为了允许用户在许多目录中导航并避免在设置选择时触发的可重入事件,我不得不对其进行一些扩展。但是,正如 Oscar 指出的那样,无法使用键盘进行导航(它总是选择焦点所在的任何内容)。如果你不使用键盘,它可以工作。

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->对不起,代码格式不太好看,但是 StackoverFlow 破坏了 KDE 和 Gnome 下的 Firefox 和 Iceweasel 代码格式支持。

于 2008-11-29T17:00:31.773 回答