我正在尝试创建一个允许用户选择项目的程序。选择项目后,将出现一个包含总价格成本的框。当我运行该程序时,我点击了一个项目,结果显示为否定。似乎我的if和else语句是错误的,我只是无法找到如何正确修复它。
package javaapplication118;
import java.awt.Color;
import java.awt.FlowLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.ItemEvent;
import java.awt.event.ItemListener;
import javax.swing.JButton;
import javax.swing.JCheckBox;
import javax.swing.JFrame;
import javax.swing.JOptionPane;
import javax.swing.JTextField;
public class pizza extends JFrame {
JTextField textField, priceField;
JCheckBox pineApple, drink, delivery, meatballs;
JButton button;
pizza() {
super("Pizza order");
setLayout(new FlowLayout());
textField = new JTextField("hello please check anything you would like to order");
textField.setEditable(false);
textField.setBackground(Color.yellow);
add(textField);
EventHandler handler = new EventHandler();
pineApple = new JCheckBox("Pine apples");
pineApple.addItemListener(handler);
add(pineApple);
drink = new JCheckBox("drink");
drink.addItemListener(handler);
add(drink);
delivery = new JCheckBox("delivery");
delivery.addItemListener(handler);
add(delivery);
meatballs = new JCheckBox("meat balls");
meatballs.addItemListener(handler);
add(meatballs);
priceField = new JTextField("$", 15);
add(priceField);
button = new JButton("confirm order");
button.addActionListener(
new ActionListener() {
public void actionPerformed(ActionEvent event) {
JOptionPane.showMessageDialog(null, "Your order has been placed.");
}
});
add(button);
}
//JTextField textField priceField
// JCheckBox pineApple, drink, delivery, meatballs;
public class EventHandler implements ItemListener {
double price = 0;
public void itemStateChanged(ItemEvent event) {
if (pineApple.isSelected()) { // if pineapple is selected add to the price
price = price + 2.30;
} else if (!pineApple.isSelected()){ // if pineapple is deselected subtract from price
price = price - 2.30;
}
if (delivery.isSelected()) {
price = price + 5;
} else if (!delivery.isSelected()) {
price = price - 5;
}
if (drink.isSelected()) {
price = price + 1;
} else if (!drink.isSelected()) {
price = price - 1;
}
if (meatballs.isSelected()) {
price = price + 1;
} else if (!meatballs.isSelected()) {
price = price - 1;
}
priceField.setText("$" + price);
}
}
}
答案 0 :(得分:3)
您似乎“假设”过去选择了一件或多件物品,但您无法知道这是否属实......
相反,请将price
重置为0
,并仅为那些实际当前选中的项目添加price
...
public void itemStateChanged(ItemEvent event) {
price = 0;
if (pineApple.isSelected()) {
price = price + 2.30;
}
if (delivery.isSelected()) {
price = price + 5;
}
if (drink.isSelected()) {
price = price + 1;
}
if (meatballs.isSelected()) {
price = price + 1;
}
priceField.setText("$" + price);
}
答案 1 :(得分:1)
您的代码会从价格中减去价值。那就是当你选择“肉丸”时它会加1价格,现在的价格是1.00美元 然后清除其他复选框(您已编码,以便在清除复选框时减去相关值)
菠萝2.30美元,送餐费5美元,饮料1.00美元(总价8.30美元)从价格“减去”。1 - 8.3 = -7.3
这就是你得到负值的原因。