【问题标题】:Check if JList contains object with changing suffix检查 JList 是否包含具有更改后缀的对象
【发布时间】:2016-10-28 21:00:16
【问题描述】:

我需要检查 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;
}

【问题讨论】:

  • 你研究过正则表达式和模式匹配吗?
  • 可能有一个侦听器设置为dml 对象,该对象在dlm.addElement() 中被调用
  • 或者使用一个类(例如ProductItem)来保存描述和价格,并适当地实现toStringequals。那样的额外学分:)
  • @PaulHicks,你愿意给我一个关于如何制作这门课的提示吗?
  • 随意删除问题或发布您自己的答案(为了他人的利益)

标签: java jlist defaultlistmodel


【解决方案1】:

我通过制作一个仅包含所选项目的单独 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;
}

【讨论】:

    猜你喜欢
    • 2012-02-02
    • 2022-11-09
    • 2019-08-24
    • 1970-01-01
    • 2018-03-08
    • 2023-03-26
    • 2013-03-25
    • 2020-06-07
    • 2021-09-18
    相关资源
    最近更新 更多