如何通过 TextField 过滤 csv 中的数据

发布于 2025-01-14 05:32:45 字数 1310 浏览 4 评论 0原文

我已经在 GUI 中添加了一个文本字段,如果输入了名称,我希望它能够过滤主机名。例如:“Amy”会在ListCell 中显示csv 文件中所有Amy 租房的情况。我添加了一个方法 searchByHost() ,我想在其中执行此操作。

这是我的代码:

public class ListingsController
{
    private ObservableList<String> comboBoxList = FXCollections.observableArrayList("Host Name: A-Z",
            "Host Name: Z-A", "Price: Low to High", "Price: High to Low", "No of Reviews: Low to High",
            "No of Reviews: High to Low");
    private List<AirbnbListing> propertyArrayList;
    private ObservableList<AirbnbListing> propertyList;
    private SortedList<AirbnbListing> sortedList;
    public TextField inputHostName;

    @FXML
    private ComboBox<String> comboBox;

    @FXML
    private ListView<AirbnbListing> listingsList;

    @FXML
    private TextField searchField;
    private String name;
    private String min;
    private String max;

    // TODO: remove at some point

    public void initialize()
    {
       
    public void setListings(List<AirbnbListing> listings)
    {
        listingsList.getItems().addAll(listings);
    }

    public void displayListing(AirbnbListing listing)
    {
        if (listing == null)
            return;
        System.out.println(listing);
    }

} 

我在网上看到的所有示例都使用过滤器和可观察列表,但我认为我不需要它。

I've added a textfield to my GUI and I want it to filter through the host names if a name in inputed. E.g.: "Amy" would display all the Amy's in the csv file renting a house in the ListCell. I've added a method searchByHost() where I'd like to do it.

Here is my code:

public class ListingsController
{
    private ObservableList<String> comboBoxList = FXCollections.observableArrayList("Host Name: A-Z",
            "Host Name: Z-A", "Price: Low to High", "Price: High to Low", "No of Reviews: Low to High",
            "No of Reviews: High to Low");
    private List<AirbnbListing> propertyArrayList;
    private ObservableList<AirbnbListing> propertyList;
    private SortedList<AirbnbListing> sortedList;
    public TextField inputHostName;

    @FXML
    private ComboBox<String> comboBox;

    @FXML
    private ListView<AirbnbListing> listingsList;

    @FXML
    private TextField searchField;
    private String name;
    private String min;
    private String max;

    // TODO: remove at some point

    public void initialize()
    {
       
    public void setListings(List<AirbnbListing> listings)
    {
        listingsList.getItems().addAll(listings);
    }

    public void displayListing(AirbnbListing listing)
    {
        if (listing == null)
            return;
        System.out.println(listing);
    }

} 

All the examples I've seen online use a filter an observable list however I don't think I'd need that.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

烟花肆意 2025-01-21 05:32:45

我使用这个将它们放在一起。它使用 SortedList 按主机名排序,并使用 FilteredList 按主机名返回搜索结果。我没有实施其他选项。其他选项应该与主机名非常相似。

import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.ThreadLocalRandom;
import javafx.application.Application;
import javafx.beans.property.DoubleProperty;
import javafx.beans.property.IntegerProperty;
import javafx.beans.property.SimpleDoubleProperty;
import javafx.beans.property.SimpleIntegerProperty;
import javafx.beans.property.SimpleStringProperty;
import javafx.beans.property.StringProperty;
import javafx.collections.FXCollections;
import javafx.collections.ObservableList;
import javafx.collections.transformation.FilteredList;
import javafx.collections.transformation.SortedList;
import javafx.scene.Scene;
import javafx.scene.control.ComboBox;
import javafx.scene.control.ListCell;
import javafx.scene.control.ListView;
import javafx.scene.control.TextField;
import javafx.scene.layout.HBox;
import javafx.scene.layout.Priority;
import javafx.scene.layout.VBox;
import javafx.stage.Stage;


public class App extends Application  {

    ObservableList<AirbnbListing> listViewItems; 
    SortedList<AirbnbListing> sortedList;
    FilteredList<AirbnbListing> filteredList;
    ComboBox<String> comboBox = new ComboBox();
    
    @Override
    public void start(Stage primaryStage) throws Exception {
        primaryStage.setTitle("ListView Example");
        
        VBox root = new VBox();  
        
        
        //Create ListView
        ListView<AirbnbListing> listView = new ListView();
        listViewItems = FXCollections.observableArrayList(getDataFromCsv());
        sortedList = new SortedList(listViewItems);
        filteredList = new FilteredList(sortedList);
        listView.setItems(filteredList);
        listView.setCellFactory((ListView<AirbnbListing> airbnbListingListView) -> new ListCell<AirbnbListing>() {
            @Override
            protected void updateItem(AirbnbListing listing, boolean empty) {
                super.updateItem(listing, empty);
                if (listing != null) {
                    setText(listing.getHostName()+ " - " + listing.getPrice() + " - " + listing.getNumberOfReviews());
                } else {
                    setText("");
                }
            }
        });
        listView.maxHeight(Double.MIN_VALUE);
        VBox.setVgrow(listView, Priority.ALWAYS);
        root.getChildren().add(listView);
        

        //Create Search Bar
        TextField searchTextField = new TextField();
        searchTextField.setPromptText("Search here!");
        searchTextField.textProperty().addListener((obs, oldValue, newValue) -> {
            switch (comboBox.getValue())//Switch on choiceBox value
            {
                case "Host Name: A-Z":                    
                case "Host Name: Z-A":
                    filteredList.setPredicate(p -> p.getHostName().toLowerCase().contains(newValue.toLowerCase().trim()));//filter table by host name
                    break;
                default:
                    System.out.println("Other cases need to be implemented!@");
                    break;
            }
        });
        
        ObservableList<String> comboBoxList = FXCollections.observableArrayList("Host Name: A-Z",
            "Host Name: Z-A", "Price: Low to High", "Price: High to Low", "No of Reviews: Low to High",
            "No of Reviews: High to Low");
        
        comboBox.setItems(comboBoxList);       
        comboBox.getSelectionModel().selectedItemProperty().addListener((obs, oldVal, newVal)
                -> {//sort and reset listview and textfield when new choice is selected
            if (newVal != null) {
                searchTextField.setText("");
                
                switch(newVal)
                {
                    case "Host Name: A-Z":                        
                        sortedList.setComparator((a,b)->{
                            return a.getHostName().compareToIgnoreCase(b.getHostName());
                        });
                        break;
                    case "Host Name: Z-A":
                        sortedList.setComparator((a,b)->{
                            return b.getHostName().compareToIgnoreCase(a.getHostName());
                        });
                        break;
                        
                    default:
                        System.out.println("Other cases need to be implemented!");
                }
            }
        });
        
        comboBox.setValue("Host Name: A-Z");
       
        
        HBox searchBarHBox = new HBox(comboBox, searchTextField);
        root.getChildren().add(searchBarHBox);

        Scene scene = new Scene(root, 500, 500);
        primaryStage.setScene(scene);
        primaryStage.show();
    }

    public static class AirbnbListing
    {

        private final StringProperty hostName = new SimpleStringProperty();
        private final DoubleProperty price = new SimpleDoubleProperty();
        private final IntegerProperty numberOfReviews = new SimpleIntegerProperty();     

        public AirbnbListing(String hostName, double price, int numberOfReviews) {
            this.hostName.setValue(hostName);
            this.price.setValue(price);
            this.numberOfReviews.setValue(numberOfReviews);
        }

        public void setHostName(String hostName)
        {
            this.hostName.setValue(hostName);
        }
        
        public void setPrice(double price)
        {
            this.price.setValue(price);
        }
        
        public void setNumberOfReviews(int numberofReviews)
        {
            this.numberOfReviews.setValue(numberofReviews);
        }
        
        public String getHostName()
        {
            return this.hostName.getValue();
        }
        
        public double getPrice()
        {
            return this.price.getValue();
        }
        
        public int getNumberOfReviews()
        {
            return this.numberOfReviews.getValue();
        }
        
        public StringProperty getHostNameProperty() {
            return this.hostName;
        }

        public DoubleProperty getPriceProperty() {
            return this.price;
        }

        public IntegerProperty getNumberOfReviewsProperty() {
            return this.numberOfReviews;
        }

        @Override
        public String toString() {
            StringBuilder sb = new StringBuilder();
            sb.append("AirbnbListing{hostName=").append(hostName.getValue());
            sb.append(", price=").append(price.getValue());
            sb.append(", numberOfReviews=").append(numberOfReviews.getValue());
            sb.append('}');
            return sb.toString();
        }        
    }
    
    public static List<AirbnbListing> getDataFromCsv()
    {       
        List<AirbnbListing> data = new ArrayList();
        
        for(int i = 0; i < 20; i++)
        {
            data.add(new AirbnbListing("Name " + ThreadLocalRandom.current().nextInt(10000), ThreadLocalRandom.current().nextDouble(0, 100), ThreadLocalRandom.current().nextInt(10)));            
        }
        
        
        return data;
    }
    
    
    public static void main(String[] args) {
        Application.launch(args);
    }
}

输入图片此处描述

I put this together using this. It uses a SortedList to sort by the host name and uses a FilteredList to return search results by host name. I did not implement the other options. The other options should be very similar to host name.

import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.ThreadLocalRandom;
import javafx.application.Application;
import javafx.beans.property.DoubleProperty;
import javafx.beans.property.IntegerProperty;
import javafx.beans.property.SimpleDoubleProperty;
import javafx.beans.property.SimpleIntegerProperty;
import javafx.beans.property.SimpleStringProperty;
import javafx.beans.property.StringProperty;
import javafx.collections.FXCollections;
import javafx.collections.ObservableList;
import javafx.collections.transformation.FilteredList;
import javafx.collections.transformation.SortedList;
import javafx.scene.Scene;
import javafx.scene.control.ComboBox;
import javafx.scene.control.ListCell;
import javafx.scene.control.ListView;
import javafx.scene.control.TextField;
import javafx.scene.layout.HBox;
import javafx.scene.layout.Priority;
import javafx.scene.layout.VBox;
import javafx.stage.Stage;


public class App extends Application  {

    ObservableList<AirbnbListing> listViewItems; 
    SortedList<AirbnbListing> sortedList;
    FilteredList<AirbnbListing> filteredList;
    ComboBox<String> comboBox = new ComboBox();
    
    @Override
    public void start(Stage primaryStage) throws Exception {
        primaryStage.setTitle("ListView Example");
        
        VBox root = new VBox();  
        
        
        //Create ListView
        ListView<AirbnbListing> listView = new ListView();
        listViewItems = FXCollections.observableArrayList(getDataFromCsv());
        sortedList = new SortedList(listViewItems);
        filteredList = new FilteredList(sortedList);
        listView.setItems(filteredList);
        listView.setCellFactory((ListView<AirbnbListing> airbnbListingListView) -> new ListCell<AirbnbListing>() {
            @Override
            protected void updateItem(AirbnbListing listing, boolean empty) {
                super.updateItem(listing, empty);
                if (listing != null) {
                    setText(listing.getHostName()+ " - " + listing.getPrice() + " - " + listing.getNumberOfReviews());
                } else {
                    setText("");
                }
            }
        });
        listView.maxHeight(Double.MIN_VALUE);
        VBox.setVgrow(listView, Priority.ALWAYS);
        root.getChildren().add(listView);
        

        //Create Search Bar
        TextField searchTextField = new TextField();
        searchTextField.setPromptText("Search here!");
        searchTextField.textProperty().addListener((obs, oldValue, newValue) -> {
            switch (comboBox.getValue())//Switch on choiceBox value
            {
                case "Host Name: A-Z":                    
                case "Host Name: Z-A":
                    filteredList.setPredicate(p -> p.getHostName().toLowerCase().contains(newValue.toLowerCase().trim()));//filter table by host name
                    break;
                default:
                    System.out.println("Other cases need to be implemented!@");
                    break;
            }
        });
        
        ObservableList<String> comboBoxList = FXCollections.observableArrayList("Host Name: A-Z",
            "Host Name: Z-A", "Price: Low to High", "Price: High to Low", "No of Reviews: Low to High",
            "No of Reviews: High to Low");
        
        comboBox.setItems(comboBoxList);       
        comboBox.getSelectionModel().selectedItemProperty().addListener((obs, oldVal, newVal)
                -> {//sort and reset listview and textfield when new choice is selected
            if (newVal != null) {
                searchTextField.setText("");
                
                switch(newVal)
                {
                    case "Host Name: A-Z":                        
                        sortedList.setComparator((a,b)->{
                            return a.getHostName().compareToIgnoreCase(b.getHostName());
                        });
                        break;
                    case "Host Name: Z-A":
                        sortedList.setComparator((a,b)->{
                            return b.getHostName().compareToIgnoreCase(a.getHostName());
                        });
                        break;
                        
                    default:
                        System.out.println("Other cases need to be implemented!");
                }
            }
        });
        
        comboBox.setValue("Host Name: A-Z");
       
        
        HBox searchBarHBox = new HBox(comboBox, searchTextField);
        root.getChildren().add(searchBarHBox);

        Scene scene = new Scene(root, 500, 500);
        primaryStage.setScene(scene);
        primaryStage.show();
    }

    public static class AirbnbListing
    {

        private final StringProperty hostName = new SimpleStringProperty();
        private final DoubleProperty price = new SimpleDoubleProperty();
        private final IntegerProperty numberOfReviews = new SimpleIntegerProperty();     

        public AirbnbListing(String hostName, double price, int numberOfReviews) {
            this.hostName.setValue(hostName);
            this.price.setValue(price);
            this.numberOfReviews.setValue(numberOfReviews);
        }

        public void setHostName(String hostName)
        {
            this.hostName.setValue(hostName);
        }
        
        public void setPrice(double price)
        {
            this.price.setValue(price);
        }
        
        public void setNumberOfReviews(int numberofReviews)
        {
            this.numberOfReviews.setValue(numberofReviews);
        }
        
        public String getHostName()
        {
            return this.hostName.getValue();
        }
        
        public double getPrice()
        {
            return this.price.getValue();
        }
        
        public int getNumberOfReviews()
        {
            return this.numberOfReviews.getValue();
        }
        
        public StringProperty getHostNameProperty() {
            return this.hostName;
        }

        public DoubleProperty getPriceProperty() {
            return this.price;
        }

        public IntegerProperty getNumberOfReviewsProperty() {
            return this.numberOfReviews;
        }

        @Override
        public String toString() {
            StringBuilder sb = new StringBuilder();
            sb.append("AirbnbListing{hostName=").append(hostName.getValue());
            sb.append(", price=").append(price.getValue());
            sb.append(", numberOfReviews=").append(numberOfReviews.getValue());
            sb.append('}');
            return sb.toString();
        }        
    }
    
    public static List<AirbnbListing> getDataFromCsv()
    {       
        List<AirbnbListing> data = new ArrayList();
        
        for(int i = 0; i < 20; i++)
        {
            data.add(new AirbnbListing("Name " + ThreadLocalRandom.current().nextInt(10000), ThreadLocalRandom.current().nextDouble(0, 100), ThreadLocalRandom.current().nextInt(10)));            
        }
        
        
        return data;
    }
    
    
    public static void main(String[] args) {
        Application.launch(args);
    }
}

enter image description here

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文