Reputation: 15
Cannot make my ButtonGroup display for the first two checkboxes. Attempted to add them, which seems successful, however the group will not show. Do you see what I did incorrectly?
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);
}
}
Receiving a "no suitable method found for add(ButtonGroup)," though I did declare it.
Upvotes: 1
Views: 1901
Reputation: 17341
You don't add the ButtonGroup
to the frame. You add the radio buttons to the group to indicate what the possible options are. You add the buttons to the frame to indicate where they should appear. These are independent concerns. (Source).
Additionally, using JRadioButton
instead of JCheckBox
will provide the user a better indication that only one can be selected.
Upvotes: 3