1

I am currently working on a project that will take theorhetical orders for Pizza. One panel I'm making will have three options for Pizza. Thin crust, regular, and deep dish. My initial thought was to use a Buttongroup, because those make it so only one can be selected at a time. However that doesn't appear to work with JPanels, as searching here I discovered. However, none of the answers here I found mentioned any other way of doing it that kept them from all being selected at once.

1 Answers1

3

The idea with the ButtonGroup is completely right. Look in the Java Api for further information.

EDIT

A minimal example would look like this:

import java.awt.GridLayout;

import javax.swing.ButtonGroup;
import javax.swing.JFrame;
import javax.swing.JRadioButton;
import javax.swing.SwingUtilities;

public class BottonGroupGui extends JFrame {

    public BottonGroupGui() {
        this.setDefaultCloseOperation(EXIT_ON_CLOSE);

        JRadioButton a = new JRadioButton("a");
        JRadioButton b = new JRadioButton("b");

        this.setLayout(new GridLayout());

        this.getContentPane().add(a);
        this.getContentPane().add(b);

        ButtonGroup group = new ButtonGroup();

        group.add(a);
        group.add(b);

        this.setVisible(true);
        this.pack();
    }

    public static void main(String[] args) {
        SwingUtilities.invokeLater(new Runnable() {
            @Override
            public void run() {
                new BottonGroupGui();
            }
        });

    }
}

You don't have to add the BottonGroup. Just assign the buttons (in my case JRadioButtons) to the group accordingly.

ROT13
  • 375
  • 2
  • 7