好的,我已经在控制台中使用扫描仪创建了一个搜索功能,但我现在想从我的 GUI 创建一个搜索功能。当文本输入到 JTextField
并单击 JButton
时,我想要一种方法,可以逐行搜索我的文本文件,直到找到搜索条件并将其打印出来进入 JOptionPane
。
文本文件中的数据格式如下:
解决这个问题的最佳方法是什么?
提前致谢
最佳答案
您已经有了搜索方法,因此请向您的按钮添加一个操作监听器,它将调用您的方法,例如:
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
,然后调用 Search
。 Search
的输入是getSearchCriteria
的返回值。在 GUI 中,您只需调用搜索(使用 JTextField 中的文本作为输入)。
关于java - 从 GUI 搜索文本文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6201157/