Textfile search from GUI
Ok so i have made a search function using scanner in console, but i would now like to create a search function from my GUI. When text is entered into a JTextField
and JButton
is clicked i would like a method which would search my text file line by line until it finds the the searched for criteria and 开发者_JS百科prints it into a JOptionPane
.
Data in text file is formatted as follows:
what would be the best way to go about this?
Thanks in Advance
You already have the search method, so add an action listener to your button, that will call your method, something like:
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
}
}
Seeing your update, you better split the search function, so it will receive the search criteria as an input, something like:
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");
}
}
}
Now, when you run it from console, you first call the getSearchCriteria
and then Search
. The input of Search
is the return value of getSearchCriteria
. In your GUI you only need to call search (with the text from the JTextField as an input).
i don't know..
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
}
}
精彩评论