Sorry if this is an easy answer or has been answered, but have searched and couldnt find anything. I am currently creating a supermarket checkout line with the products in a DefaultListModel, each product having a name, price, weight and code as shown below
public class Product {
private String name;
private double weight;
private double price;
private int code;
public Product (){
}
public Product (String Name, double kg, double pounds, int id){
name = Name;
weight = kg;
price = pounds;
code = id;
public String toString (){
return name + " - " + "£" + price + " Product # " + code;
and the products put into a list
public class productList extends DefaultListModel {
public productList (){
super();
}
public void addProduct (String name, double weight, double price, int code){
super.addElement(new Product(name, weight, price, code));
this has been used in the GUI for the checkout in the code segments as follows
private DefaultListModel defaultMainList = new DefaultListModel();
//other code
currentBasket.setModel(defaultMainList); //currentBasket is name of jlist
productsList = new productList();
productsList.addProduct("bananas", 0.5, 0.99, 1);
productsList.addProduct("apples", 0.8, 1.39, 2);
//etc etc, other products emitted
mainCheckoutList.setModel(productsList);
//unimportant code
addBasketItem = new JButton();
getContentPane().add(addBasketItem);
addBasketItem.setText("Add >");
addBasketItem.setBounds(215, 108, 62, 31);
addBasketItem.addActionListener(new ActionListener(){
public void actionPerformed (ActionEvent e){
defaultMainList.addElement(productsList.getElementAt(mainCheckoutList.getSelectedIndex()));
mainTillPrice.setText((defaultMainList.toString()));
this current code adds the item from the jlist on the left (main checkout list, which is my list of available products) to the jlist on the right which is my basket. It also adds the entire string of characters in the right list to the jtextfield called mainTillPrice, i want to know if there is any way just to add the price, eg. for the bananas object add 0.99, and then with subsequent items added add their prices as well to keep a running total. Any help would be appreciated and again sorry for any problems in explanation or code, i am fairly new.
Well, I wouldn't be using defaultMainList.toString()
. You will need to get the Product
which is been added, get the price
of the Product
and add it to the current tally. This value would then need to be added to the mainTillPrice
text field
public void actionPerformed (ActionEvent e){
Product product = (Product)mainCheckoutList.getSelectedItem();
defaultMainList.addElement(product);
runningTally += product.getPrice();
mainTillPrice.setText(NumberFormat.getCurrencyInstance().format(runningTally));
This will require you to create an instance field called runningTally
and assumes you have a method getPrice
in your Product