简体   繁体   English

如何在 JList 中按属性搜索项目

[英]how can I search an item by property in a JList

I have an item class and I store items in a JList, I would like to look for an item in a JList by the name of the item.我有一个项目类,我将项目存储在 JList 中,我想通过项目名称在 JList 中查找项目。 I have a JButton called search that implements the next code, and nameToSearch variable gets the string written in a JTextfield,我有一个名为 search 的 JButton,它实现了下一个代码,nameToSearch 变量获取写入 JTextfield 的字符串,

  ArrayList<Item> backUp = new ArrayList<>();
            ArrayList<Item> itemsFound = new ArrayList<>();

            for (int i = 0; i < listModel.getSize(); i++) {
                backUp.add(listModel.getElementAt(i));

                if (listModel.getElementAt(i).getName().compareToIgnoreCase(nameToSearch) >= 0) {
                    Item foundItem = listModel.getElementAt(i);
                    itemsFound.add(foundItem);
                }
            }
                //clear the listModel to display the found items
                listModel.removeAllElements();
                //add the found items to the listModel to be displayed
                for (Item s: itemsFound) {
                    listModel.addElement(s);}

I meant to get all the items in a backup arrayList to show all of the items later, the if statement checks is the item.getName() is is what the user is looking for and it adds that element to a itemfound ArrayList, it is supposed to have the item found in the arrayList, then i remove all the elements from the defaultListModel listmodel and then add the found items in the defaultListModel listModel so the found items are the only ones on the JList for that moment.我的意思是让备份 arrayList 中的所有项目稍后显示所有项目,if 语句检查是 item.getName() 是用户正在寻找的内容,并将该元素添加到 itemfound ArrayList,它是应该在 arrayList 中找到项目,然后我从 defaultListModel listmodel 中删除所有元素,然后将找到的项目添加到 defaultListModel listModel 中,这样找到的项目是当时 JList 上唯一的项目。 But this doesnt work,it doesnt do anything.但这不起作用,它什么也没做。 any suggestion on how to do it is well appreciated非常感谢有关如何做的任何建议

A very simple solution can be to:一个非常简单的解决方案可以是:

  1. Store all items into a collection of your preference, or array.将所有项目存储到您喜欢的集合或数组中。
  2. Use a DefaultListModel (which is programmatically dynamic) for the JList .JList使用DefaultListModel (以编程方式动态)。
  3. For each search operation clear the model and then add one after another the items which match the search criteria.对于每个搜索操作,清除模型,然后一个接一个地添加符合搜索条件的项目。

For example:例如:

import java.awt.BorderLayout;
import java.util.Arrays;
import java.util.List;
import java.util.Objects;
import javax.swing.DefaultListModel;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JList;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTextField;

public class Main {

    //Assuming the class Item is similar to the following implementation:
    public static class Item {
        private final String name;

        public Item(final String name) {
            this.name = Objects.requireNonNull(name);
        }

        public String getName() {
            return name;
        }

        //Overriding toString method, to avoid implementing a custom ListCellRenderer...
        @Override
        public String toString() {
            return getName();
        }
    }

    public static void main(final String[] args) {

        //The following list contains all the initial Items lets say:
        final List<Item> allItems = Arrays.asList(new Item("abc"), new Item("ABC"),
                                                  new Item("def"), new Item("DEF"));

        //Create a DefaultListModelof Items (which is programmatically dynamic):
        final DefaultListModel<Item> listModel = new DefaultListModel<>();

        //Supply the model to the list on creation time (or later with setModel):
        final JList<Item> list = new JList<>(listModel);

        //Initialize the listModel to initially contain all items:
        allItems.forEach(item -> listModel.addElement(item));

        final JTextField searchField = new JTextField(10);
        final JButton searchButton = new JButton("Search");
        searchButton.addActionListener(e -> {
            final String searchText = searchField.getText();
            listModel.clear();
            if (searchText.isEmpty()) //If the search text field is empty, lets say we want to display all values:
                allItems.forEach(item -> listModel.addElement(item));
            else
                allItems.forEach(item -> {
                    if (item.getName().equalsIgnoreCase(searchText))
                        listModel.addElement(item);
                });
        });
        final JPanel pageStart = new JPanel(); //FlowLayout
        pageStart.add(searchField);
        pageStart.add(searchButton);
        final JPanel all = new JPanel(new BorderLayout());
        all.add(pageStart, BorderLayout.PAGE_START);
        all.add(new JScrollPane(list), BorderLayout.CENTER);
        final JFrame frame = new JFrame("Searchable JList");
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        frame.getContentPane().add(all);
        frame.pack();
        frame.setLocationRelativeTo(null);
        frame.setVisible(true);
    }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM