【问题标题】:How to search through arraylist containing string, int and double with JTextField and JButton如何使用 JTextField 和 JButton 搜索包含字符串、int 和 double 的数组列表
【发布时间】:2013-12-04 03:48:41
【问题描述】:

我目前有一个工作的 GUI 程序,上面有几个按钮可以简单地逐步浏览我的项目数组列表。这些只是显示第一个、最后一个或下一个和上一个索引结果。该列表包含Stringintdouble。现在我添加了一个JTextField 用于输入和一个搜索按钮。我的问题是如何让我的搜索按钮来搜索这个数组列表?我正在阅读this answer,但我不明白基准的事情。在搜索之前是否必须将整个数组列表转换为字符串?像

    ArrayList<inventoryItem> inventory = new ArrayList<>();  ....    
    JTextField input = new JTextField(18); ...
          JButton searchButton = new JButton("Search");
            searchButton.setToolTipText("Search for entry");


searchButton.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent ae) {
                String usrInput = input.getText();
                for (String s : inventory) {
                    if (usrInput.contains(s)) {
                        inventory.get(currentIndex);
                        outputText.append(" somehow put whatever the index is equal to here");

                    }

                }

            }
        });

我得到的错误是inventoryItem cannot be converted to string。第二个问题:我遇到的是如何让它输出该索引中的所有内容。例如,我的输出如下所示:

class officeSupplyItem extends inventoryItem {

    public officeSupplyItem(String itemName, int itemNumber, int inStock, double unitPrice) {
        super(itemName, itemNumber, inStock, unitPrice);
    }

    @Override
    public void output(JTextArea outputText) {
        outputText.setText("Item Name = " + itemName + " \n"); //print out the item name
        outputText.append("Item Number = " + itemNumber + " \n"); //print out the item number
        outputText.append("In Stock = " + inStock + " \n"); //print out how many of the item are in stock
        outputText.append("Item Price = $" + formatted.format(unitPrice) + " \n"); //print out the price per item
        outputText.append("Restocking fee is $" + formatted.format(restockingFee) + " per item \n");
        outputText.append("Value of item inventory = $" + formatted.format(value) + " \n"); //print out the value of the item inventory
        outputText.append("Cost of inventory w/restocking fee = $" + formatted.format(inventoryValue) + " \n"); //print out the total cost of inventory with restocking fee

    }
}

我还想了解上述链接的基准部分的含义。

【问题讨论】:

    标签: java search user-interface netbeans arraylist


    【解决方案1】:

    我不太清楚你所说的“这个列表里面有 String、int 和 double”是什么意思。

    您正在将对象字段与输入的文本进行比较。您无需将 InventoryItem 转换为字符串。您需要做的是确定要比较的字段并在比较中使用它们。

    从我看到的输入到 JTextField 的文本是您的代码的搜索条件。如果我假设它是 itemName,你的代码应该如下:

    searchButton.addActionListener(new ActionListener() {  
           @Override  
            public void actionPerformed(ActionEvent ae) {
                String usrInput = input.getText();
                for (InventoryItem s : inventory) {
                    if (usrInput.equalsIgnoreCase(s.getItemName())) {
                        //you can call output string here
                        outputText.append(" somehow put whatever the index is equal to here");
    
                    }
                }
    
            }
        });
    

    这适用于 JTextField 输入是 itemName 的情况。如果这与您的预期不同,请发表评论。

    从你分享的链接来看,不同之处在于他的列表只包含字符串,这就是为什么“数据”是一个字符串。这不能用于您的情况。

    希望这会有所帮助!

    【讨论】:

    • 我的整个代码都在这里(方便分享)link 看看你是否能理解我在做什么。提前抱歉,因为它太笨重了。出于某种原因,它不喜欢我使用 s.getitemName()
    • getItemName 应该是您类中的 getter 方法,是否存在?无法在工作中打开 pastebin:/
    【解决方案2】:

    根据我的理解,无论 searchText 是什么(itemName 或 itemNumber),都应该列出结果。因此,您可以在 InventoryItem 类中编写一个搜索方法,比较并返回是否与搜索字符串匹配,如下所示。

    public boolean isSearchTextAvailable(String searchText) {
        if (this.itemName.equals(searchText)) {
            return true;
        } else {
            try {
                int no = Integer.parseInt(searchText);
                if (this.itemNumber == no) {
                    return true;
                }
            } catch (NumberFormatException e) {
                System.out.println("Not a integer");
            }
        }
        return false;
    }
    

    您可以将此方法增强到要在其中搜索的任意数量的字段。

    然后在 searchButton 的操作中使用此方法。

      searchButton.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent ae) {
    
                String usrInput = input.getText();
    
                for (InventoryItem invItem : inventory) {
                    if (invItem.isSearchTextAvailable(usrInput)) {
                        invItem.output(outputText);
                    }
                }
    
            }
        });
    

    您必须将输入 (JTextField) 设为此类中的一个字段才能使其正常工作。

    提高代码质量的一些技巧:

    • InventoryItemOfficeSupplyItem 类分开到不同的文件中
    • 注意类名的命名约定是 PascalCase
    • 最好从 JFrame 扩展 JavaGUIFixed 类,并将其所有组件定义为字段而不是局部变量,因为您在实际创建 JFrame 的 makeWindow() 方法以外的各种其他方法中使用它们
    • 不要使用invItem.output(outputText) 类型的方法,其中你将一个JTextField 传递给一个对象方法来写入它。您可以做的是在 InventoryItem 类中编写类似 getOutputString() 的方法,该方法将返回需要打印的格式化字符串,然后调用 outputText.setText(invItem.getOutputString()) - 您的实现限制您将所有类都作为 JavaGUIFixed 的内部类。

    希望这会有所帮助!

    【讨论】:

      【解决方案3】:

      您的增强 for 循环表示 ArrayList 库存中的每个 String 元素 s...但是库存被声明为 inventoryItem 对象的 ArrayList,而不是字符串列表,并且 for 循环不访问变量您尝试搜索的值被存储,因为每个库存索引只是存储对对象的引用。

      如果您的主要目标是获取输入、存储、排序和输出,您可以考虑将其作为字符串存储在字符串集合中。如果需要,您始终可以解析为 int 或 double,但使用同质数据类型进行排序和搜索会更容易。

      我看到该链接中使用的数据只是作为变量名,与您在代码中使用“s”的方式相同。

      【讨论】:

        【解决方案4】:

        我已将@maheeka 的回复标记为答案。然而,由于我之前编写程序的方式,我不得不修改他的代码。现在看起来如下:

        searchButton.addActionListener(new ActionListener() {
                @Override
                public void actionPerformed(ActionEvent ae) {
                    String usrInput = input.getText();
                    for (int i = 0; i < inventory.size(); i++) {
                        if (usrInput.equalsIgnoreCase(inventory.get(i).getItemName())) {
                            currentIndex = i;
                            displayItem(outputText);
        

        我还必须在 itemName 上设置我的 getter,因为我显然忘记了那部分。谢谢@Aadi Droid。

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 1970-01-01
          • 2013-08-04
          • 1970-01-01
          • 2016-04-11
          • 1970-01-01
          • 2015-02-06
          • 2017-07-04
          • 2021-02-27
          相关资源
          最近更新 更多