Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/java/400.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
在JavaFX中使用多个choicebox筛选listview_Java_Listview_Javafx_Fxml_Scenebuilder - Fatal编程技术网

在JavaFX中使用多个choicebox筛选listview

在JavaFX中使用多个choicebox筛选listview,java,listview,javafx,fxml,scenebuilder,Java,Listview,Javafx,Fxml,Scenebuilder,我正在尝试使用多个ChoiceBox为我的listview创建一个过滤器函数,但我不知道如何做,因为我对JavaFX非常陌生 我做了一些研究,听说需要使用filteredList,但大多数在线示例都只使用文本字段 这是我的控制器类 @FXML 私人选择框体裁; @FXML 私人选箱部; @FXML 私人选择箱状态; @FXML 私人ChoiceBox公司; @FXML 私有列表视图列表视图; 私有ObservableList movieList=FXCollections.observableA

我正在尝试使用多个ChoiceBox为我的listview创建一个过滤器函数,但我不知道如何做,因为我对JavaFX非常陌生

我做了一些研究,听说需要使用filteredList,但大多数在线示例都只使用文本字段

这是我的控制器类

@FXML 私人选择框体裁; @FXML 私人选箱部; @FXML 私人选择箱状态; @FXML 私人ChoiceBox公司; @FXML 私有列表视图列表视图; 私有ObservableList movieList=FXCollections.observableArrayList; private FilteredList filteredData=new FilteredListmovieList,s->true; 公共控制员{ vehicleList.addAll 新电影《恐怖,IT》,Branch1,上映,华纳兄弟, 新动作片,约翰·威克3号,第2分册,即将上映,顶峰娱乐 ; @凌驾 public void初始值设定项URL位置,ResourceBundle资源{ //我计划在这里用initialize方法实现过滤器 listView.setItemsfilteredData; listView.setCellFactorymovieListView->新建MovieListViewCell; } 这是MovieListViewCell类

@FXML 自有品牌类型; @FXML 自有品牌地位; @FXML 私有网格窗格; 私人FXMLLoader; @凌驾 受保护的无效更新视频电影,布尔值为空{ super.updateItemvehicle,空; 如果为空| |车辆==空{ setTextnull; setGraphicnull; }否则{ 如果mLLoader==null{ mLLoader=new FXMLLoadergetClass.getResource/application/ListCell.fxml; mLLoader.setControllerthis; 试一试{ mLLoader.load; }捕捉异常{ e、 打印跟踪; } } genre.setTextString.valueOfvehicle.getMovie_流派; status.setTextString.valueOfvehicle.getMovie_status; setTextnull; 设置图形网格窗格; } } 这是我运行整个UI的主要方法

公共类主扩展应用程序{ @凌驾 公共空间开始阶段初级阶段{ 试一试{ 父根=FXMLLoader.loadgetClass.getResource/application/MainPage.fxml; 场景=新场景,800650; 初生阶段;初生阶段; 初级舞台表演; }卡奇{ e、 打印跟踪; } } 公共静态无效字符串[]args{ 发射艇; } } 这是我的FXML主布局MainPage.FXML

这是ListCell.fxml


希望有人能为我提供任何解决方案。谢谢你考虑过之后,我可以使用简单的版本来演示,它应该适合你更复杂的版本。关键是为每个ChoiceBox创建一个侦听器。当ChoiceBox选择更改时,更新FilteredList谓词

你需要的代码

完整示例

如果要筛选内存中的项,使用FilteredList是正确的方法。如果查看,您将看到FilteredList有一个谓词属性。毫不奇怪,该属性包含一个。谓词接口是一个函数接口,这意味着它可以是抽象的lambda表达式或方法引用的目标方法接受类型为T和retu的泛型参数 基于任意逻辑的rns true或false。设置FilteredList的谓词属性时,它将使用谓词确定源ObservableList中的元素是否应通过FilteredList视图可见。随着项目从源ObservableList中添加和删除,FilteredList将自动更新

不幸的是,如果您更新谓词所基于的任何状态,例如在ChoiceBox中选择的选项,它将不会自动对源ObservableList的所有元素重新应用谓词。换句话说,FilteredList不会仅仅因为谓词的内部状态已更改而自动更新。这意味着每次更新过滤器状态时,都需要创建新的谓词并设置FilteredList的谓词属性。这就是创建和使用绑定将很有帮助的地方。注意:虽然Callable是java.util.concurrent包的一部分,但这里没有并发

要创建绑定,我们将使用。该方法接受另一个功能接口和一组可观察对象。观察值数组称为已创建ObjectBinding的依赖项,当其中任何一个无效时,会导致ObjectBinding基于给定的可调用项重新计算其值。换句话说,每次一个可观察对象失效时都会调用Callable

FilteredList<Movie> filteredList = movieList.filtered(null); // a null Predicate means "always true"

// moved to own variable for clarity (usually inlined with the method call)
Observable[] dependencies = {genre.valueProperty(), branch.valueProperty(), status.valueProperty(), company.valueProperty()};

ObjectBinding<Predicate<Movie>> binding = Bindings.createObjectBinding(() -> {
    Predicate<Movie> predicate = movie -> {
        // test "movie" based on the values of your ChoiceBoxes
    };
    return predicate;
}, dependencies);

filteredList.predicateProperty().bind(binding);

如果您注意到,依赖项是每个ChoiceBox的属性。属性,即ReadOnlyProperty和Property的实例是Observable的实现,当它们的值可能发生更改时,它们将失效。这意味着每当用户更改其选择时,value属性将无效,并且FilteredList的谓词将更改。当谓词更改时,列表将重新过滤。

这可能是一个复杂的问题。我想答案取决于ListView单元格的外观。如果只是一个字符串,这是一个更简单的答案。如果它是一个节点布局,它会更复杂。我会编辑并发布我的fxml代码添加MovieListViewCell@Sedrick好的,希望如此helps@Slaw答案可能需要更少的编码,可能是最好的方法。如何用4个选项框实现它?我尝试用4个ChoiceBox实现,它运行,但对某些组合不起作用。我建议您使用Slaw的答案。随着您添加更多选择,这将变得更加复杂。
import javafx.application.Application;
import javafx.collections.FXCollections;
import javafx.collections.ObservableList;
import javafx.collections.transformation.FilteredList;
import javafx.scene.Scene;
import javafx.scene.control.ChoiceBox;
import javafx.scene.control.ListCell;
import javafx.scene.control.ListView;
import javafx.scene.layout.HBox;
import javafx.scene.layout.VBox;
import javafx.stage.Stage;
/**
 *
 * @author Sedrick
 */
public class JavaFXApplication38 extends Application {

    @Override
    public void start(Stage primaryStage) {
        ChoiceBox<String> cbGenre = new ChoiceBox();
        cbGenre.getItems().addAll("All", "Horror", "Action");
        cbGenre.setValue("All");
        ChoiceBox<String> cbBranch = new ChoiceBox();
        cbBranch.getItems().addAll("All", "Branch1", "Branch2");
        cbBranch.setValue("All");

        ObservableList<Movie> movieList = FXCollections.observableArrayList();
        movieList.add(new Movie("Horror", "IT", "Branch1", "Released", "Warner Bros"));
        movieList.add(new Movie("Action","John Wick 3" ,"Branch2", "Coming Soon", "Summit Entertainment"));
        FilteredList<Movie> filteredData = new FilteredList<>(movieList, s -> true);

        ListView<Movie> listView = new ListView<>(filteredData);
        listView.setCellFactory((ListView<Movie> param) -> {
            ListCell<Movie> cell = new ListCell<Movie>() {                
                @Override
                protected void updateItem(Movie item, boolean empty) {
                    super.updateItem(item, empty);
                    if (item != null) {
                        setText(item.getTitle());
                    } else {
                        setText("");
                    }
                }
            };

            return cell;
        });

        cbBranch.getSelectionModel().selectedItemProperty().addListener((obs, oldValue, newValue) ->{
             System.out.println("Branch: " + newValue);
            filteredData.setPredicate((t) -> {

                switch(cbGenre.getValue())
                {
                    case "All":
                        switch(newValue)
                        {
                            case "All":
                                return true;
                            default:
                                return newValue.equals(t.getBranch());                                
                        }

                    default:
                        return newValue.equals(t.getBranch()) && cbGenre.getValue().equals(t.getGenre());
                }
            });
        });
        cbGenre.getSelectionModel().selectedItemProperty().addListener((obs, oldValue, newValue)->{
            System.out.println("Genre: " + newValue);
            filteredData.setPredicate((t) -> {
                switch(cbBranch.getValue())
                {
                    case "All":
                        switch(newValue)
                        {
                            case "All":
                                return true;
                            default:
                                return newValue.equals(t.getGenre());
                        }
                    default:
                        return newValue.equals(t.getGenre()) && cbGenre.getValue().equals(t.getBranch());
                }
            });
        });

        HBox root = new HBox(new VBox(cbBranch, cbGenre), listView);

        Scene scene = new Scene(root, 300, 250);

        primaryStage.setTitle("Hello World!");
        primaryStage.setScene(scene);
        primaryStage.show();
    }

    /**
     * @param args the command line arguments
     */
    public static void main(String[] args) {
        launch(args);
    }

}
import javafx.application.Application;
import javafx.collections.FXCollections;
import javafx.collections.ObservableList;
import javafx.collections.transformation.FilteredList;
import javafx.scene.Scene;
import javafx.scene.control.ChoiceBox;
import javafx.scene.control.ListCell;
import javafx.scene.control.ListView;
import javafx.scene.layout.HBox;
import javafx.scene.layout.VBox;
import javafx.stage.Stage;
/**
 *
 * @author Sedrick
 */
public class JavaFXApplication38 extends Application {

    @Override
    public void start(Stage primaryStage) {
        ChoiceBox<String> cbGenre = new ChoiceBox();
        cbGenre.getItems().addAll("All", "Horror", "Action");
        cbGenre.setValue("All");
        ChoiceBox<String> cbBranch = new ChoiceBox();
        cbBranch.getItems().addAll("All", "Branch1", "Branch2");
        cbBranch.setValue("All");
        ChoiceBox<String> cbRelease = new ChoiceBox();
        cbRelease.getItems().addAll("All", "Released", "Coming Soon");
        cbRelease.setValue("All");
        ChoiceBox<String> cbParentCompany = new ChoiceBox();
        cbParentCompany.getItems().addAll("All", "Warner Bros", "Summit Entertainment");
        cbParentCompany.setValue("All");
        ChoiceBox<String> cbTitle = new ChoiceBox();
        cbTitle.getItems().addAll("All", "IT", "John Wick 3");
        cbTitle.setValue("All");


        ObservableList<Movie> movieList = FXCollections.observableArrayList();
        movieList.add(new Movie("Horror", "IT", "Branch1", "Released", "Warner Bros"));
        movieList.add(new Movie("Action","John Wick 3" ,"Branch2", "Coming Soon", "Summit Entertainment"));
        FilteredList<Movie> filteredData = new FilteredList<>(movieList, s -> true);

        ListView<Movie> listView = new ListView<>(filteredData);
        listView.setCellFactory((ListView<Movie> param) -> {
            ListCell<Movie> cell = new ListCell<Movie>() {                
                @Override
                protected void updateItem(Movie item, boolean empty) {
                    super.updateItem(item, empty);
                    if (item != null) {
                        setText(item.getTitle());
                    } else {
                        setText("");
                    }
                }
            };

            return cell;
        });
        cbRelease.getSelectionModel().selectedItemProperty().addListener((obs, oldValue, newValue) ->{
             System.out.println("Released: " + newValue);
            filteredData.setPredicate((t) -> {               
                return (cbBranch.getValue().equals("All") ? true : t.getBranch().equals(cbBranch.getValue())) && 
                       (cbGenre.getValue().equals("All") ? true : t.getGenre().equals(cbGenre.getValue())) && 
                       (cbParentCompany.getValue().equals("All") ? true : t.getParentCompany().equals(cbParentCompany.getValue())) &&
                       (cbTitle.getValue().equals("All") ? true : t.getTitle().equals(cbTitle.getValue())) && 
                       (cbRelease.getValue().equals("All") ? true : t.getRelease().equals(cbRelease.getValue()));
            });
        });
        cbBranch.getSelectionModel().selectedItemProperty().addListener((obs, oldValue, newValue) ->{
             System.out.println("Branch: " + newValue);

            filteredData.setPredicate((t) -> {
                return (cbBranch.getValue().equals("All") ? true : t.getBranch().equals(newValue)) && 
                       (cbGenre.getValue().equals("All") ? true : t.getGenre().equals(cbGenre.getValue())) && 
                       (cbParentCompany.getValue().equals("All") ? true : t.getParentCompany().equals(cbParentCompany.getValue())) &&
                       (cbTitle.getValue().equals("All") ? true : t.getTitle().equals(cbTitle.getValue())) && 
                       (cbRelease.getValue().equals("All") ? true : t.getRelease().equals(cbRelease.getValue()));
            });
        });
        cbGenre.getSelectionModel().selectedItemProperty().addListener((obs, oldValue, newValue)->{
            System.out.println("Genre: " + newValue);
            filteredData.setPredicate((t) -> {
                return (cbBranch.getValue().equals("All") ? true : t.getBranch().equals(cbBranch.getValue())) && 
                       (cbGenre.getValue().equals("All") ? true : t.getGenre().equals(cbGenre.getValue())) && 
                       (cbParentCompany.getValue().equals("All") ? true : t.getParentCompany().equals(cbParentCompany.getValue())) &&
                       (cbTitle.getValue().equals("All") ? true : t.getTitle().equals(cbTitle.getValue())) && 
                       (cbRelease.getValue().equals("All") ? true : t.getRelease().equals(cbRelease.getValue()));
            });
        });

        cbParentCompany.getSelectionModel().selectedItemProperty().addListener((obs, oldValue, newValue)->{
            System.out.println("parent company: " + newValue);
            filteredData.setPredicate((t) -> {
                return (cbBranch.getValue().equals("All") ? true : t.getBranch().equals(cbBranch.getValue())) && 
                       (cbGenre.getValue().equals("All") ? true : t.getGenre().equals(cbGenre.getValue())) && 
                       (cbParentCompany.getValue().equals("All") ? true : t.getParentCompany().equals(cbParentCompany.getValue())) &&
                       (cbTitle.getValue().equals("All") ? true : t.getTitle().equals(cbTitle.getValue())) && 
                       (cbRelease.getValue().equals("All") ? true : t.getRelease().equals(cbRelease.getValue()));
            });
        });

        cbTitle.getSelectionModel().selectedItemProperty().addListener((obs, oldValue, newValue)->{
            System.out.println("title: " + newValue);
            filteredData.setPredicate((t) -> {
                return (cbBranch.getValue().equals("All") ? true : t.getBranch().equals(cbBranch.getValue())) && 
                       (cbGenre.getValue().equals("All") ? true : t.getGenre().equals(cbGenre.getValue())) && 
                       (cbParentCompany.getValue().equals("All") ? true : t.getParentCompany().equals(cbParentCompany.getValue())) &&
                       (cbTitle.getValue().equals("All") ? true : t.getTitle().equals(cbTitle.getValue())) && 
                       (cbRelease.getValue().equals("All") ? true : t.getRelease().equals(cbRelease.getValue()));
            });
        });

        HBox root = new HBox(new VBox(cbBranch, cbGenre, cbRelease, cbParentCompany, cbTitle), listView);

        Scene scene = new Scene(root, 300, 250);

        primaryStage.setTitle("Hello World!");
        primaryStage.setScene(scene);
        primaryStage.show();
    }

    /**
     * @param args the command line arguments
     */
    public static void main(String[] args) {
        launch(args);
    }

}
FilteredList<Movie> filteredList = movieList.filtered(null); // a null Predicate means "always true"

// moved to own variable for clarity (usually inlined with the method call)
Observable[] dependencies = {genre.valueProperty(), branch.valueProperty(), status.valueProperty(), company.valueProperty()};

ObjectBinding<Predicate<Movie>> binding = Bindings.createObjectBinding(() -> {
    Predicate<Movie> predicate = movie -> {
        // test "movie" based on the values of your ChoiceBoxes
    };
    return predicate;
}, dependencies);

filteredList.predicateProperty().bind(binding);