[英]How do I sum the total amount based on selected checkbox
How can I sum the total amount of all the checkbox I chose? 如何汇总我选择的所有复选框的总数?
public class Frame extends JFrame implements ItemListener{
JLabel lbl1=new JLabel("SERVICES");
JLabel price1=new JLabel("100.00");
JLabel price2=new JLabel("200.00");
JLabel price3=new JLabel("300.00");
JCheckBox haircut=new JCheckBox("Hair Cut");
JCheckBox fullcolor=new JCheckBox("Full Color");
JCheckBox hairrebond=new JCheckBox("Hair Rebond");
JPanel first = new JPanel();
JPanel second= new JPanel();
JPanel third = new JPanel();
double price,total;
public Frame(){
FlowLayout flow = (new FlowLayout(FlowLayout.LEFT, 30,30));
add(lbl1);
first.add(hairrebond);
first.add(price1);
second.add(haircut);
second.add(price2);
third.add(fullcolor);
third.add(price3);
add(first);
add(second);
add(third);
setLayout(flow);
setVisible(true);
setSize(600,600);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}
@Override
public void itemStateChanged(ItemEvent e) {
if(hairrebond.isSelected()==true){
price=100;
total += price;
}
if(fullcolor.isSelected()==true){
price=400;
total += price;
}if(haircut.isSelected()==true){
price=500;
total += price;
}
}
public static void main(String args[]){
Frame one = new Frame();
}}
Try this code out. 试试这个代码。 Key is to use a local variable inside itemStateChanged method. 关键是在itemStateChanged方法内使用局部变量。
import java.awt.FlowLayout;
import java.awt.event.ItemEvent;
import java.awt.event.ItemListener;
import javax.swing.JCheckBox;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
public class Frame extends JFrame implements ItemListener {
JLabel lbl1 = new JLabel("SERVICES");
JLabel price1 = new JLabel("100.00");
JLabel price2 = new JLabel("200.00");
JLabel price3 = new JLabel("300.00");
JCheckBox haircut = new JCheckBox("Hair Cut");
JCheckBox fullcolor = new JCheckBox("Full Color");
JCheckBox hairrebond = new JCheckBox("Hair Rebond");
JPanel first = new JPanel();
JPanel second = new JPanel();
JPanel third = new JPanel();
double price, total;
public Frame() {
FlowLayout flow = (new FlowLayout(FlowLayout.LEFT, 30, 30));
add(lbl1);
first.add(hairrebond);
first.add(price1);
second.add(haircut);
second.add(price2);
third.add(fullcolor);
third.add(price3);
add(first);
add(second);
add(third);
setLayout(flow);
setVisible(true);
setSize(600, 600);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
haircut.addItemListener(this);
fullcolor.addItemListener(this);
hairrebond.addItemListener(this);
}
@Override
public void itemStateChanged(ItemEvent e) {
int sum = 0;
if (hairrebond.isSelected() == true) {
sum += 100;
}
if (fullcolor.isSelected() == true) {
sum += 300;
}
if (haircut.isSelected() == true) {
sum += 200;
}
total = sum;
System.out.println(total);
}
public static void main(String args[]) {
Frame one = new Frame();
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.