【问题标题】:Textfile search from GUI从 GUI 搜索文本文件
【发布时间】:2011-09-06 06:25:09
【问题描述】:

好的,所以我在控制台中使用扫描仪创建了一个搜索功能,但我现在想从我的 GUI 创建一个搜索功能。当文本输入到JTextField 并单击JButton 时,我想要一种方法,它可以逐行搜索我的文本文件,直到找到搜索到的条件并将其打印到JOptionPane

文本文件中的数据格式如下:

最好的方法是什么?

提前致谢

【问题讨论】:

    标签: java swing search text-files


    【解决方案1】:

    你已经有了搜索方法,所以给你的按钮添加一个动作监听器,它会调用你的方法,比如:

    myButton.addActionListener(new ActionListener() {
    
        public void actionPerformed(ActionEvent e) {
            String whatToSearch = myTextField.getText();
            String result = yourSearchMethod(whatToSearch);
            // use the fitting method of JOptionPane to display the result
        }
    }
    

    看到您的更新,您最好拆分搜索功能,这样它将接收搜索条件作为输入,例如:

    public class SearchProp {
         public String getSearchCriteria()
         {
                Scanner user = new Scanner(System.in);
                System.out.println();
                System.out.println();
                System.out.println("Please enter your Search: ");
                input = user.next();
         }
    
         public void Search(String input) throws FileNotFoundException{
            try{
                String details, id, line;
                int count;
                Scanner housenumber = new Scanner(new File("writeto.txt"));
                while(housenumber.hasNext())
                {
                    id = housenumber.next();
                    line = housenumber.nextLine();
                    if(input.equals(id))
                    {
                        JOptionPane.showMessageDialog(null,id + line );
                        break;
                    }
                    if(!housenumber.hasNext())      
                         System.out.println("No Properties with this criteria");
                }
           }
    
           catch(IOException e)
           {
                System.out.print("File failure");
           }
       }
    }
    

    现在,当您从控制台运行它时,您首先调用getSearchCriteria,然后调用SearchSearch 的输入是getSearchCriteria 的返回值。在您的 GUI 中,您只需要调用搜索(使用 JTextField 中的文本作为输入)。

    【讨论】:

    • 我了解您建议的 ActionListener,但我当前的搜索类依赖于扫描仪,如果您有机会查看,我已在我编辑的问题中发布了我当前的搜索方法
    • 我看到了,看到了我的更新,并将输入和实际搜索分开到不同的方法中,这将为您提供更大的灵活性,就像您现在需要的那样。
    • 我得休息一下了,我只是想找到如何将这两种方法分开。
    • 不是我通常的做法,但我会给你一个例子。
    • 非常感谢,这更有意义。我刚刚错过了一些细节。
    【解决方案2】:

    我不知道..

    myButton.addActionListener(new ActionListener() {
    
        public void actionPerformed(ActionEvent e) {
            String whatToSearch = myTextField.getText();
            String result = yourSearchMethod(whatToSearch);
            // use the fitting method of JOptionPane to display the result
        }
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2015-12-25
      • 2023-03-28
      • 1970-01-01
      • 2019-12-03
      • 2012-03-10
      • 1970-01-01
      相关资源
      最近更新 更多