【发布时间】:2016-11-20 15:53:35
【问题描述】:
如何计算我选择的所有复选框的总金额?
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();
}}
【问题讨论】:
-
什么问题?你没有添加itemchange监听器?
-
当您调用将返回 true 或 false 布尔值的 isSelected() 时,如果条件为 true,则 if 语句将执行,因此使用 == true 是在浪费您的时间真的。一个更好的写法是
if(fullcolor.isSelected()){//do stuff}另一个需要注意的是java命名约定(你如何命名你的变量,类等),遵守这些标准将提高代码的可读性see the naming conventions here -
至于为什么没有调用您的侦听器,我相信这是因为尽管您实现了 itemlistener,但您实际上并未将其添加到任何设备中,但可以像这样
haircut.addItemListener(this);
标签: java swing jframe jcheckbox