我需要检查JList / DefaultListModel是否包含一个项目。我正在检查的项目是一个字符串,它在" $"之后发生变化。登录。
以下是我正在使用的代码的伪版本。
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;
}
答案 0 :(得分:0)
我通过创建一个仅包含所选项目的单独DefaultListModel来解决问题。这用于验证IF语句。
以下是工作代码:
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;
}