[英]How to get the result of only CHECKED checkboxes and count Total
我正在做宠物项目并使用 NetBeans JFrame。 我遇到了一个问题,我只能计算一个选中的 chexBox Total 。 但是我如何实现一种方法或 smth,它可以帮助计算所有已检查的 chexBoxes 的总数。 很高兴回答我如何实施和计算检查价格? 这是我的代码和下面的截图
private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {
// TODO add your handling code here:
double Total = 0.0;
if(cbCappuccino.isSelected()){
String Cappucino = chboxCappucino.getValue().toString();
int boom1 = Integer.parseInt(Cappucino);
Total = boom1 * 1.0;
}
else if(cbAmericano.isSelected()){
String Americano = chboxAmericano.getValue().toString();
int boom2 = Integer.parseInt(Americano);
Total = Total+boom2 * 1.50;
}
else if(cbLatte.isSelected()){
String Latte = chboxLatte.getValue().toString();
int boom3 = Integer.parseInt(Latte);
Total = Total + boom3 * 2.50;
}
totalText.setText(Double.toString(Total));
}
就像@maloomeister 和@vincrichaud 建议我这样做:
if(cbCappuccino.isSelected()){
String Cappucino = chboxCappucino.getValue().toString();
int boom1 = Integer.parseInt(Cappucino);
Total = Total+ boom1 * 1.0;
}
if(cbAmericano.isSelected()){
String Americano = chboxAmericano.getValue().toString();
int boom2 = Integer.parseInt(Americano);
Total = Total+boom2 * 1.50;
}
if(cbLatte.isSelected()){
String Latte = chboxLatte.getValue().toString();
int boom3 = Integer.parseInt(Latte);
Total = Total + boom3 * 2.50;
}
totalText.setText(Double.toString(Total));
我只是取出 if-else 语句并放入 if 语句,并添加Total = Total + etc
为了获得更好的 OOP 解决方案,请考虑将每个项目表示为封装单个行项目的视图和属性的对象:
import java.awt.*;
import javax.swing.*;
class Item extends JPanel{
private final JCheckBox selected;
private final JComboBox<Integer> qty;
private final double price;
private final String name;
private static final Integer[] QTYS = {0,1,2,3,4,5,6,7,8,9};
public Item(String name, double price) {
this.price = price;
this.name = name;
selected = new JCheckBox(name, false);
qty = new JComboBox<>(QTYS);
qty.setSelectedIndex(0);
setLayout(new GridLayout(1, 0, 15, 0));
add(selected);
add(qty);
JLabel cost = new JLabel(String.format("%,.2f", price), JLabel.CENTER);
add(cost);
}
public boolean isSelected() {
return selected.isSelected();
}
public int getQty() {
return (int)qty.getSelectedItem();
}
public double getPrice() {
return price;
}
public double getTotal() {
return isSelected() ? getQty()*getPrice() : 0;
}
@Override
public String getName() {
return name;
}
}
去做:
clear()
方法 旁注:考虑使用JList
作为所有项目的父容器。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.