我正在尝试更新totalOrderedLabel,以便当我从orderList中删除一个项目时,totalOrderedLabel中的totalPrice将会更新。
删除按钮
JButton removeButton = new JButton("remove");
removeButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
int selectionNumber = orderList.getSelectedIndex();
if (selectionNumber == -1) {
JOptionPane.showMessageDialog(MenuPage.this, "Remove Item");
} else {
listOrder.removeElementAt(selectionNumber);
double totalPrice = 0.0;
for(Food food : OrderedFoodList) {
totalPrice = totalPrice + food.getPrice();
}
totalOrderedLabel.setText("Total price: " + totalPrice);
OrderedFoodList.clear();
}
}
});
removeButton.setBounds(680, 189, 117, 29);
contentPane.add(removeButton);
orderList /方法来累计总价格。
menulist listOrder = new menulist();
orderList = new JList(listOrder);
JButton orderBtn = new JButton();
orderBtn.setText("Place Order");
orderBtn.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
int selectionNumber = mealList.getSelectedIndex();
if (selectionNumber == -1){
JOptionPane.showMessageDialog(MenuPage.this, "Please select a meal");
} else {
Food orderedMeal = (Food) mealList.getSelectedValue();
JOptionPane.showMessageDialog(MenuPage.this, "You have ordered " //clear the last order . find a code to do that
+ orderedMeal + "");
listOrder.addElement(orderedMeal);
double totalPrice = 0.0;
for(Food food : OrderedFoodList) {
totalPrice = totalPrice + food.getPrice();
}
totalOrderedLabel.setText("Total price: " + totalPrice);
}
}
});
orderBtn.setBounds(259, 189, 117, 29);
contentPane.add(orderBtn);
totalOrdered Label
totalOrderedLabel = new JLabel("Total Price");
totalOrderedLabel.setBounds(697, 111, 142, 16);
contentPane.add(totalOrderedLabel);
totalCaloriesLabel = new JLabel("Total Calories");
totalCaloriesLabel.setBounds(388, 205, 253, 16);
contentPane.add(totalCaloriesLabel);
}
public void updateLabel(menulist model) {
int selectionNumber = mealList.getSelectedIndex();
if (selectionNumber == -1){
//JOptionPane.showMessageDialog(MenuPage.this, "Please select a meal");
} else {
Food menulist = (Food) mealList.getSelectedValue();
Food itemFood = (Food) ((menulist) model).getElementAt(selectionNumber);
//Add new food to current order
OrderedFoodList.add(itemFood);
答案 0 :(得分:0)
我正在尝试更新我的totalOrderedLabel,以便当我从orderList中删除一个项目时,totalOrderedLabel中的totalPrice将会更新
当你在列表中添加新项目时呢?在这两种情况下,概念都是相同的,您遍历列表中的所有项目,然后更新标签。
因此,当列表中的项目发生变化时,您需要得到通知。向ListDataListener
添加ListModel
。然后,当生成事件时,您遍历列表中的所有剩余项目并重新计算总数,然后更新JLabel。
阅读How to Write a ListDataListener上Swing教程中的部分,以获取有关工作示例和更多信息。