【发布时间】:2015-03-14 07:59:01
【问题描述】:
到目前为止,我有一个具体问题正在努力解决。我正在开发一个特定的应用程序,用户可以通过 JCheckBoxes 选择保险选项。
我使用了 ButtonGroup 来允许用户仅选择两种保险类型之一 - HMO(健康维护组织)或 PPO(首选提供者组织)。我使用常规(单个)JCheckBoxes 进行牙科保险和视力保险选项;用户可以选择一个选项、两个选项或一个都不选。当用户选择每个选项时,其名称和价格会显示在文本字段中; HMO 每月 200 美元,PPO 每月 600 美元,牙科保险每月增加 75 美元,视力保健每月增加 20 美元。当用户取消选择一个项目时,文本字段将变为空白。请看下面我写的代码。
public class JInsurance extends JFrame implements ItemListener{
private JTextField t1;
private JRadioButton hmo, ppo;
private JCheckBox dental, visual;
private JLabel lbl;
private ButtonGroup grp;
public double total;
public JInsurance(){
setBounds(100, 100, 450, 300);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
getContentPane().setLayout(null);
grp = new ButtonGroup();
hmo = new JRadioButton("HMO");
hmo.setBounds(21, 53, 109, 23);
hmo.setActionCommand("hmo");
grp.add(hmo);
add(hmo);
ppo = new JRadioButton("PPO");
ppo.setBounds(21, 101, 109, 23);
ppo.setActionCommand("ppo");
grp.add(ppo);
add(ppo);
dental = new JCheckBox("Dental Insurance");
dental.setBounds(178, 53, 135, 23);
add(dental);
visual = new JCheckBox("Visual Insurance");
visual.setBounds(178, 101, 118, 23);
add(visual);
lbl = new JLabel("You have chosen");
lbl.setFont(new Font("Tahoma", Font.BOLD, 12));
lbl.setBounds(41, 193, 109, 23);
add(lbl);
t1 = new JTextField();
t1.setBounds(152, 181, 179, 45);
add(t1);
t1.setColumns(10);
hmo.addItemListener(this);
ppo.addItemListener(this);
dental.addItemListener(this);
visual.addItemListener(this);
}
public void itemStateChanged(ItemEvent e){
if (hmo.isSelected())
if(dental.isSelected())
total = 200 + 75;
else if(dental.isSelected() && visual.isSelected())
total = 200 + 75 + 20;
else if(visual.isSelected())
total = 200 + 20;
t1.setText(String.valueOf(total));
if(ppo.equals("PPO"))
if(dental.isSelected())
total = 600 + 75;
else if(dental.isSelected() && visual.isSelected())
total = 600 + 75 + 20;
else if(visual.isSelected())
total = 600 + 20;
t1.setText(String.valueOf(total));
}
【问题讨论】:
-
帮自己一个忙,在
#itemStateChanged()中的if/else构造中添加大括号。 -
并使用布局管理器....有什么问题?
-
您似乎遇到了“悬空其他”问题。
-
@MadProgrammer - 问题主要出在 itemStateChanged 方法上。我认为我无法适当地实现该功能
标签: java swing jcheckbox jradiobutton buttongroup