javajlistdefaultlistmodel

Check if JList contains object with changing suffix


I need to check if a JList / DefaultListModel contains an item. The item I am checking is a String that changes after a "$" sign.

Here is a pseudo version of the code I'm working with.

String theItem = "Bananas";
BigDecimal theQuantity = new BigDecimal(quantity.getText());
BigDecimal thePrice = new BigDecimal(0.00); //This changes depending on quanitity
thePrice = thePrice.setScale(2, BigDecimal.ROUND_HALF_UP);

if (!dlm.contains(whatGoesHere)) {
    dlm.addElement(theItem + " $" + thePrice.toString());
    jList.setModel(dlm);
    //More code
} else {
    JOptionPane.showMessageDialog(mainPanel, "You already selected that item", "Error Dialog", JOptionPane.ERROR_MESSAGE);
    return;
}

Solution

  • I solved the problem by making a separate DefaultListModel which contains only the selected item. This is used in the validation IF Statement.

    Here is the working code:

    DefaultListModel validatorDLM = new DefaultListModel();  //Specifically for validation
    DefaultListModel orderDLM = new DefaultListModel();
    String theItem = "Bananas";  //This changes with combo box
    BigDecimal theQuantity = new BigDecimal(quantity.getText());
    BigDecimal thePrice = new BigDecimal(0.00); //This changes depending on quanitity
    thePrice = thePrice.setScale(2, BigDecimal.ROUND_HALF_UP);
    
    if (!validatorDLM.contains(theItem)) {
        validatorDLM.addElement(theItem);
        orderDLM.addElement(theItem + " $" + thePrice.toString());
        jList.setModel(orderDLM);
        //More code
    } else {
        JOptionPane.showMessageDialog(mainPanel, "You already selected that item", "Error Dialog", JOptionPane.ERROR_MESSAGE);
        return;
    }