基本上,这个简单的程序所做的是在您单击按钮时显示摘要,披萨大小有三个单选按钮,浇头有三个复选框。我遇到的问题是,当用户第一次单击浇头,然后单击按钮并在 MessageDialog 中显示适当的摘要后,当用户想要没有浇头时,它不会显示“未选择浇头”
import java.applet.Applet;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.ItemEvent;
import java.awt.event.ItemListener;
import java.awt.*;
import javax.swing.*;
public class PizzaOrdering extends Applet implements ActionListener, ItemListener {
Button btnOk = new Button("OK");
CheckboxGroup cbgSize = new CheckboxGroup();
Checkbox chkSmall = new Checkbox("Small", cbgSize, false);
Checkbox chkMedium = new Checkbox("Medium", cbgSize, false);
Checkbox chkLarge = new Checkbox("Large", cbgSize, false);
Checkbox chkPep = new Checkbox("Pepperoni");
Checkbox chkMush = new Checkbox("Mushroom");
Checkbox chkAnch = new Checkbox("Anchiovies");
String pizza = "";
String topping1 = "";
String topping2 = "";
String topping3 = "";
String others = "with no toppings";
Label lbl1 = new Label("Size");
Label lbl2 = new Label("Toppings");
Label spacer = new Label(" ");
Label spacer2 = new Label(" ");
@Override
public void init() {
resize(250, 150);
add(lbl1);
add(spacer);
add(chkSmall);
add(chkMedium);
add(chkLarge);
add(lbl2);
add(spacer2);
add(chkPep);
add(chkMush);
add(chkAnch);
add(btnOk);
chkAnch.addItemListener(this);
chkPep.addItemListener(this);
chkMush.addItemListener(this);
btnOk.addActionListener(this);
}
@Override
public void actionPerformed(ActionEvent e) {
if (e.getSource() == btnOk) {
if (cbgSize.getSelectedCheckbox() == chkSmall) {
pizza = "Small";
}
if (cbgSize.getSelectedCheckbox() == chkMedium) {
pizza = "Medium";
}
if (cbgSize.getSelectedCheckbox() == chkLarge) {
pizza = "Large";
}
JOptionPane.showMessageDialog(btnOk, "You ordered a " +
pizza + " pizza " + others, "Your Order", WIDTH);
}
}
@Override
public void itemStateChanged(ItemEvent ex) {
boolean state1 = false;
boolean state2 = false;
boolean state3 = false;
if (ex.getItemSelectable() == chkMush) {
state1 = chkMush.getState();
if (state1 == true) {
topping1 = "Mushroom";
} else if (state1 == false) {
topping1 = "";
if (state2 == false && state3 == false) {
others = "with no toppings";
}
}
}
if (ex.getItemSelectable() == chkPep) {
state2 = chkPep.getState();
if (state2 == true) {
topping2 = "Pepperoni";
} else if (state2 == false) {
topping2 = "";
if (state1 == false && state3 == false) {
others = "with no toppings";
}
}
}
if (ex.getItemSelectable() == chkAnch) {
state3 = chkAnch.getState();
if (state3 == true) {
topping3 = "Anchiovies";
} else if (state3 == false) {
topping3 = "";
if (state1 == false && state2 == false) {
others = "with no toppings";
}
}
}
others = " with the following topping:" +
topping1 + " " + topping2 + " " + topping3;
}
}