JavaFX使用FileFilter过滤ListView File元素

时间:2015-08-07 18:45:31

标签: java search javafx filefilter

我有一个JavaFX应用程序,它显示特定目录的所有文件夹并监视新的/删除的文件夹并更新ListView

现在,我尝试让用户使用TextField过滤/搜索文件夹 我之前已经这样做了,所以这是相关的代码:

@Override
public void initialize(URL location, ResourceBundle resources) {
    // configure other stuff
    configureListView();
}

private void configureListView() {
    searchField.textProperty().addListener((observable, oldVal, newVal) -> {
        handleSearchOnType(observable, oldVal, newVal);
    });
    // more stuff here
}

private void handleSearchOnType(ObservableValue observable, String oldVal, String newVal) {
    File folderToSearch = new File(config.getDlRootPath());
    ObservableList<File> filteredList = FXCollections.observableArrayList(folderToSearch.listFiles(
            pathname -> pathname.isDirectory() && pathname.getName().contains(newVal))); // something seems wrong here?!
    if (!searchField.getText().isEmpty()) {
        listView.setItems(filteredList);
    } else {
        // nothing to filter
        listView.setItems(FXCollections.observableArrayList(
            folderToSearch.listFiles(pathname -> pathname.isDirectory())));
        }
    }

这给了我奇怪的结果,例如:

no search search for 'test'

我在这里缺少什么?

提前谢谢!

修改:

我的自定义单元工厂

listView.setCellFactory(new Callback<ListView<File>, ListCell<File>>() {
            @Override
            public ListCell<File> call(ListView<File> list) {
                return new ListCell<File>() {
                    @Override
                    protected void updateItem(File t, boolean bln) {
                        super.updateItem(t, bln);
                        if (t != null) {
                            setGraphic(new ImageView(new Image("img/folder.png")));
                            setText(t.getName());
                        }
                    }

                };
            }
        });

1 个答案:

答案 0 :(得分:3)

不确定这是否是唯一的错误,但您的自定义单元工厂需要处理单元格为空的情况:

final Image image = new Image("img/folder.png");

listView.setCellFactory(new Callback<ListView<File>, ListCell<File>>() {
    @Override
    public ListCell<File> call(ListView<File> list) {
        return new ListCell<File>() {
            private final ImageView imageView = new ImageView(image);
            @Override
            protected void updateItem(File t, boolean bln) {
                super.updateItem(t, bln);
                if (t == null) {
                    setGraphic(null);
                    setText(null);
                } else {
                    setGraphic(imageView);
                    setText(t.getName());
                }
            }

        };
    }
});

这里的要点是,当你开始过滤时,一些先前不为空的单元格将变为空。将在这些单元格上调用updateItem(null, true),然后需要清除所有内容(否则它们只保留以前的内容)。

(对于奖励,我还会稍微重构一下,以便每次用户滚动列表视图时,不会在每个单元格中继续加载图像文件中的图像。)