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

时间:2019-04-23 22:58:19

标签: java jlist

我有一个项目类,我将项目存储在JList中,我想按项目名称在JList中查找项目。我有一个名为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);}

我的意思是获取备份arrayList中的所有项目以稍后显示所有项目,if语句检查的是item.getName()是用户正在寻找的对象,并将该元素添加到itemfound ArrayList中,应该在arrayList中找到该项目,然后我从defaultListModel listmodel中删除所有元素,然后将找到的项目添加到defaultListModel listModel中,以便该项目是当时JList上唯一的项目。 但这不起作用,它什么也没做。对此的任何建议都将受到赞赏

1 个答案:

答案 0 :(得分:0)

一个非常简单的解决方案可以是:

  1. 将所有项目存储到您的首选项或数组的集合中。
  2. JList使用DefaultListModel(程序上是动态的)。
  3. 对于每个搜索操作,请清除模型,然后依次添加与搜索条件匹配的项目。

例如:

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);
    }
}