无法使我的ButtonGroup显示为前两个复选框。尝试添加它们,似乎很成功,但是该组不会显示。看到我做错了吗?

  import javax.swing.*;
  import java.awt.*;
  import java.awt.event.*;

  public class JCottageFrame extends
  JFrame implements ItemListener {

     final int ONE_BEDROOM = 650;
     final int TWO_BEDROOM = 850;
     final int ROW_BOAT = 60;
     int totalPrice;

     ButtonGroup group = new ButtonGroup();

     JCheckBox oneBed = new JCheckBox
  ("One Bedroom/week $" + ONE_BEDROOM, false);

     JCheckBox twoBed = new
  JCheckBox("Two Bedroom/week $" + TWO_BEDROOM, false);
     JCheckBox boat = new JCheckBox ("Boat/week $" + ROW_BOAT, false);

     JLabel resortLabel = new JLabel ("Koch's Cottages Weekly Rentals");
     JLabel priceLabel = new JLabel("The price for your stay is");

     JTextField totPrice = new JTextField(4);
     JLabel optionExplainLabel2 = new JLabel
  ("Check the rentals you wish to purchase.");


     public JCottageFrame() {

        super("JCottageFrame");
        setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

        setLayout(new FlowLayout());

        add(resortLabel);
        add(optionExplainLabel2);
        group.add(oneBed);
        group.add(twoBed);
        add(group);  //This does not seem to be working correctly
        add(boat);
        add(priceLabel);
        add(totPrice);

        totPrice.setText("$" + totalPrice);

        oneBed.addItemListener(this);
        twoBed.addItemListener(this);
        boat.addItemListener(this);
     }
        public void itemStateChanged(ItemEvent event) {
        Object source = event.getSource();
        int select = event.getStateChange();

        if(source == oneBed)
        if(select == ItemEvent.SELECTED)
           totalPrice += ONE_BEDROOM;
           else
              totalPrice -= ONE_BEDROOM;
           else
              if(source == twoBed) {
              if(select == ItemEvent.SELECTED)
                 totalPrice += TWO_BEDROOM;
                    else
                       totalPrice -= TWO_BEDROOM;
              }
              else
                 if(select == ItemEvent.SELECTED)
                    totalPrice += ROW_BOAT;
                    else
                       totalPrice -= ROW_BOAT;
                       totPrice.setText("$" + totalPrice);
        }

        public static void main(String[] args)
  {
           JCottageFrame aFrame =
  new JCottageFrame();
           final int WIDTH = 270;
           final int HEIGHT = 230;
           aFrame.setSize(WIDTH, HEIGHT);
           aFrame.setVisible(true);

           aFrame.setLocationRelativeTo(null);
  }
  }


收到“没有找到适合add(ButtonGroup)的方法”,尽管我确实声明了它。

最佳答案

您无需将ButtonGroup添加到框架中。您将单选按钮添加到组中以指示可能的选项。您将按钮添加到框架以指示它们应出现的位置。这些是独立的问题。 (Source)。

此外,使用JRadioButton代替JCheckBox将为用户提供更好的指示,表明只能选择一个。

10-08 02:03