【问题标题】:It is possible to NOT add the typed wildcards in JFileChooser's file type combobox?可以不在 JFileChooser 文件类型组合框中添加类型通配符吗?
【发布时间】:2015-02-27 16:18:43
【问题描述】:

我需要一个 JFileChooser,它在保存模式下的行为类似于 notepad.exemspaint.exe。您可能知道,当您在 文件名 字段中键入通配符(* 或?)时,文件视图将仅显示与用户输入匹配的文件。这没关系,但我的问题是 Files of type 组合框:

JFileChooser 中:当用户在文件名 字段中输入通配符时,文件类型 组合框也会更新。 见截图here

但是如果你用notepad.exe 试试这个,你会发现文件名 字段和以前一样,所以搜索模式没有更新。 见记事本截图here

所以我的问题是:有人知道如何实现文件类型组合框不应该被输入的过滤器更新吗?

我需要一个跨平台的解决方案,所以它应该可以在 XP 和 Linux 上运行。

提前致谢!

对不起链接,但我不能直接附加它!

【问题讨论】:

    标签: java swing jfilechooser


    【解决方案1】:

    glob pattern 识别功能在每个外观的FileChooserUI 委托中实现。例如,MetalFileChooserUI 包含一个嵌套的ApproveSelectionAction,它继承自BasicFileChooserUI,它调用setFileFilter()。这通过PropertyChangeEvent 将新模式添加到监听MetalFileChooserUI.FilterComboBoxModel。您可能能够在链的某处拦截添加的过滤器。

    您还可以利用 Java 7 中引入的 file pattern matching 功能并讨论了 here

    【讨论】:

    • 这个相关的example可以用来检查上述事件的顺序。
    【解决方案2】:

    终于找到了解决办法: 使用派生自 BasicFileChooserUI 的自定义文件选择器 UI 将通过以下方式解决我的问题:我已经使用自定义操作覆盖了 getApproveSelectionAction() 方法:

    protected class CustomApproveSelectionAction extends BasicFileChooserUI.ApproveSelectionAction {
    
        @Override
        public void actionPerformed(ActionEvent e) {
            String filename = getFileName();
            // using a custom pattern to accept valid charachters only:
            Matcher matcher = pattern.matcher(filename);
    
            if (matcher.matches()) { 
                // this is the good case, just let the super implementation do what have to do.
                super.actionPerformed(e);
            } else {
                // this is the bad case, we must warn the user and don't let the super implementation take effect.
                // display an error message similar like notepad does it.
            }
        }
    }
    

    如果文件名没问题,那么我允许 super 实现做什么,否则我会显示一条消息。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2018-10-26
      • 1970-01-01
      • 2011-05-05
      • 2018-07-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多