Reputation: 65
So my program lets users enter words in a JTextField that acts as an input field and then stores them in the JList. After that, they can remove words by entering the word in another input box. My problem is that it will remove the words that match the users case sensitivity, but not the words that don't (e.g. if the list has the words "dog", "DOG", and "Dog" and the user types to remove "dog", it will remove the "dog" entry, but not the other ones). How would I go about remedying this?
My code so far for specifically removing words is just this:
DefaultListModel hList = new DefaultListModel();
JList list = new JList(hList);
JButton submit = new JButton("Submit");
submit.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent actionEvent) {
while (list.contains(userInput.getText())){
list.removeElement(userInput.getText());
}
I've tried doing stuff such as using equalsIgnoreCase but I don't think I'm doing it right.
Any help would be appreciated.
Upvotes: 0
Views: 57
Reputation: 44854
You can iterate and convert
String[] data = {"one", "two", "three", "four"};
JList<String> myList = new JList<String>(data);
final String find = "Two";
for (int x = 0; x < myList.getModel().getSize(); x++) {
if (myList.getModel().getElementAt(x).compareToIgnoreCase(find) == 0) {
System.out.println("Found at index " + x);
}
}
To remove though you will have to use a DefaultListModel
String[] data = {"one", "two", "three", "four"};
DefaultListModel<String> add = new DefaultListModel<String>();
for (String str : data)
add.addElement(str);
JList<String> myList = new JList<String>(add);
final String find = "Two";
for (int x = 0; x < myList.getModel().getSize(); x++) {
if (myList.getModel().getElementAt(x).compareToIgnoreCase(find) == 0) {
System.out.println("Found at index " + x);
DefaultListModel<String> model = (DefaultListModel<String>)myList.getModel();
model.remove(x);
}
}
Upvotes: 2