我正在尝试创建一个允许用户选择项目的程序。选择项目后,将出现一个带有总价格成本的框。当我运行程序时,我点击了一个项目,结果是否定的。似乎我的 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);
}
}
}