Java JRadioButton在来回选择时不断向变量添加double

时间:2017-03-30 22:40:48

标签: java swing actionlistener jradiobutton

当我选择单选按钮"六"时,它将6.00添加到变量" total",然后当我选择单选按钮"十二"它将8.00添加到变量" total"。我试图这样做,例如,当我选择按钮6时,它将仅添加6.00而当我点击十二时不会添加8.00。

class Size extends JPanel
{
  private static final long serialVersionUID = 1L;
  JLabel length = new JLabel("Select Sandwich Size");
  JPanel sizePanel = new JPanel();
  JRadioButton six = new JRadioButton("6 Inch"); 
  JRadioButton twelve = new JRadioButton("12 Inch");
  ButtonGroup group = new ButtonGroup();

  public Size()
  {
    setBackground(Color.WHITE);
    add(length, BorderLayout.NORTH);
    sizePanel.add(six);
    sizePanel.add(twelve);
    add(sizePanel, BorderLayout.SOUTH);
    group.add(six);
    group.add(twelve);

    //Radio button listener which adds size cost to variable total
    class SizeListener implements ActionListener {
      public void actionPerformed(ActionEvent event) {

        if (six.isSelected()) total += 6.00;
        else if (twelve.isSelected()) total += 8.00;

      }
    }

    ActionListener listener = new SizeListener();
    six.addActionListener(listener);
    twelve.addActionListener(listener);

  }

}

0 个答案:

没有答案