aweig
aweig

Reputation: 9

Ignore case in search field

I can not figure out where to put equalsIgnoreCase() or toLowerCase() in my code. I'm trying to make it so the search field ignores the case of the users input.

@FXML private void searchForPart(KeyEvent event) {
        if (!partSearch.getText().trim().isEmpty()) {
            partsInventorySearch.clear();
            errorLabel.setText("");
            for (Part p : partsInventory) {
                if (p.getName().contains(partSearch.getText().trim()))
                    partsInventorySearch.add(p);
                else if (Integer.toString(p.getPartID()).contains(partSearch.getText().trim()))
                    partsInventorySearch.add(p);
            }
            if (partsInventorySearch.isEmpty())
                errorLabel.setText("No parts found");
            partTable.setItems(partsInventorySearch);
        }
        else {
            errorLabel.setText("");
            partTable.setItems(partsInventory);
        }
        partTable.refresh();
    }

Upvotes: 0

Views: 69

Answers (1)

Nowhere Man
Nowhere Man

Reputation: 19565

If you need to use contains you should convert both parts of such comparison to the same case.

Also it's better to replace pasting the same code with a single variable:

@FXML
private void searchForPart(KeyEvent event) {
    String search = partSearch.getText().trim().toLowerCase();
    
    if (!search.isEmpty()) {
        partsInventorySearch.clear();
        errorLabel.setText("");
        
        for (Part p : partsInventory) {
            if (p.getName().toLowerCase().contains(search)
               || Integer.toString(p.getPartID()).contains(search)) {
                partsInventorySearch.add(p);
            }
        }
        if (partsInventorySearch.isEmpty())
            errorLabel.setText("No parts found");
        partTable.setItems(partsInventorySearch);
    }
    else {
        errorLabel.setText("");
        partTable.setItems(partsInventory);
    }
    partTable.refresh();
}

Upvotes: 2

Related Questions