user1080390
user1080390

Reputation: 471

Search an arraylist by the contents of a JTextField - arraylist.contains(jtextfield)

Currently, I'm trying to write a system, which is focused around inputting data into lists and arraylists, and implementing search and sort functionality.

Currently on my system, I have:

A class to store data An arraylist class which gets data from an object within the data storage class. And finally, a swing GUI class, which contains a JList which displays the Arraylist.

What i'm trying to do is search through the arraylist with a JButton actionlistener, and then output the results on the search to the JList.

The JButton would take the contents of a JTextField, and check if the string is present in the ArrayList.

My question first of all is, how would I go about creating a search function in the arraylist class, and call the contents of a JTextField in a seperate class?

Secondly, would I need to convert the jtextfield to a string before I could call a .contains method on the arraylist?

and thirdly, once the search function is implemented, how would I go about selecting a record from the arraylist if the text searched for is present

Here is my Data storage class: http://pastebin.com/hwyD8r1j

My arraylist class: http://pastebin.com/d3ftLsJb

I'm not expecting you guys to write it for me, although that would be nice, haha.

But any pointers or insight on how I could go about implementing this functionality into my arraylist would be appreciated,

Oh and if you need me to post my GUI class, just ask.

Upvotes: 0

Views: 1744

Answers (1)

I82Much
I82Much

Reputation: 27326

Call 'getText' on the JTextField to get the string that they've entered. You'll basically do something like the following.

// Somehow you've initialized your array list
List<String> data = ...;

// within your action listener - invoked when the button is clicked.  You'll need to
// make sure the textField is "final"
String selected = textfield.getText();
// Linear search through your strings for one matching your text
for (String datum : data) {
  if (selected.contains(datum)) {
    // do whatever you want here; you found a match
  }
}

Upvotes: 3

Related Questions