1

无法让我的 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) 的方法”,尽管我确实声明了它。

4

1 回答 1

3

你不添加ButtonGroup到框架。您将单选按钮添加到组中以指示可能的选项是什么。您将按钮添加到框架中以指示它们应该出现的位置。这些是独立的问题。(来源)。

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

于 2014-07-30T17:53:43.143 回答