从GUI搜索文本文件

Dar*_*ess 2 java search swing text-files

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

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

什么是最好的方式去做?

提前致谢

MBy*_*ByD 5

您已经有了搜索方法,因此请在按钮中添加一个动作侦听器,它将调用您的方法,例如:

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
    }
}
Run Code Online (Sandbox Code Playgroud)

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

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");
       }
   }
}
Run Code Online (Sandbox Code Playgroud)

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