2016-10-28 10 views
0

JList/DefaultListModelにアイテムが含まれているかどうかを確認する必要があります。私がチェックしている項目は、 "$"記号の後に変化する文字列です。JListに接尾辞が変更されたオブジェクトが含まれているかどうかをチェック

ここに私が作業しているコードの擬似バージョンがあります。

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

'dlm.addElement()'内で呼び出される 'dml'オブジェクトに設定されたリスナーが存在する可能性があります。 –

+0

また、説明や価格を保持するためにクラス(例:' Product'や 'Item') toString'と 'equals'を適切に使います。そのような余分なクレジット:) –

答えて

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; 
} 
関連する問題