我正在为一个类创建一个Java applet,我们使用单选按钮来选择交付或执行账单计算器。交付选项有费,但执行没有。我试图编写只会添加一次送货费用的代码,无论点击送货按钮多少次。
如下所示,每次点击发送单选按钮时,都会收取费用,并且每次点击结转时,都会扣除发送费用金额。任何想法如何确保费用只适用于交付一次或根本不适用于结转?
// Create a panel to hold two radio buttons
JPanel jrbOptions = new JPanel(new GridLayout(2 , 1));
jrbOptions.add(jrbPickUp = new JRadioButton("Pick Up - free"));
jrbOptions.add(jrbDelivery = new JRadioButton("Delivery - $4.00"));
jrbPickUp.setSelected(true);
add(jrbOptions, BorderLayout.WEST);
//Create a radio button group to group two buttons
ButtonGroup group1 = new ButtonGroup();
group1.add(jrbPickUp);
group1.add(jrbDelivery);
jrbDelivery.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
if (jrbDelivery.isSelected()) {
totalPrice += deliveryFee;
total.setText(String.valueOf(totalPrice));
}
}
});
jrbPickUp.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
if (jrbPickUp.isSelected()) {
totalPrice -= deliveryFee;
total.setText(String.valueOf(totalPrice));
}
}
});
答案 0 :(得分:0)
您需要一个可在触发ActionListener
jrbDelivery
时设置的标记,例如...
// instance field...
private boolean feeApplied = false;
//...
jrbDelivery.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
if (jrbDelivery.isSelected() && !feeApplied) {
feeApplied = true;
totalPrice += deliveryFee;
total.setText(String.valueOf(totalPrice));
}
}
});
您也可以使用它来删除投放费用(feeApplied
为true
时)
答案 1 :(得分:0)
您应该有一个与UI分离的干净数据模型。运费应该是一个单独的领域。然后,您可以通过修改数据模型来启用/禁用费用:
这是数据模型,应该在一个单独的类中(例如ShoppingCart):
public class ShoppingCart {
private double price;
private double deliveryFee;
// other fields (e.g. the list of ordered items)
public double getTotalPrice() {
return price + deliveryFee;
}
public void setDeliveryFee(double fee) {
this.deliveryFee = fee;
}
// other getters/setters...
}
然后您可以在UI中使用它:
private ShoppingCart cart;
// ...
jrbDelivery.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
if (jrbDelivery.isSelected()) {
cart.setDeliveryFee(deliveryFee); // update model
updateUI();
}
}
});
jrbPickUp.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
if (jrbPickUp.isSelected()) {
cart.setDeliveryFee(0.0); // update model
updateUI();
}
}
});
方法updateUI
:
total.setText(formatter.format(cart.getTotalPrice()));
// do other UI updates here too!
在提交时,ShoppingCart
被移交给提交机制,然后提交机制可以从对象中检索数据并将其发送到订购系统。
改进:考虑让您的数据模型bean能够在更改时发送通知(事件)。然后你可以挂钩监听器,在更改时自动更新UI!