【发布时间】:2011-09-06 06:25:09
【问题描述】:
好的,所以我在控制台中使用扫描仪创建了一个搜索功能,但我现在想从我的 GUI 创建一个搜索功能。当文本输入到JTextField 并单击JButton 时,我想要一种方法,它可以逐行搜索我的文本文件,直到找到搜索到的条件并将其打印到JOptionPane。
文本文件中的数据格式如下:
最好的方法是什么?
提前致谢
【问题讨论】:
标签: java swing search text-files
好的,所以我在控制台中使用扫描仪创建了一个搜索功能,但我现在想从我的 GUI 创建一个搜索功能。当文本输入到JTextField 并单击JButton 时,我想要一种方法,它可以逐行搜索我的文本文件,直到找到搜索到的条件并将其打印到JOptionPane。
文本文件中的数据格式如下:
最好的方法是什么?
提前致谢
【问题讨论】:
标签: java swing search text-files
你已经有了搜索方法,所以给你的按钮添加一个动作监听器,它会调用你的方法,比如:
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 中的文本作为输入)。
【讨论】:
我不知道..
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
}
}
【讨论】: