Search code examples
javaswingjradiobuttonbuttongroup

Why are my radiobuttons not mutually exclusive?


I am trying to implement two radiobuttons and make them mutually exclusive.

    public ProvincesPanel() {
    //radiobuttons definitions.csv
    this.setName("Provinces 2");
    ButtonGroup vanillaOrMod = new ButtonGroup();
    vanillaOrMod.add(rdbDefNew);
    vanillaOrMod.add(rdbDefVan);
    rdbDefNew= new JRadioButton("new definition.csv file");
    rdbDefVan= new JRadioButton("vanilla definition.csv file");
    add(rdbDefNew);
    add(rdbDefVan);
    }

Now for some reason that I don't understand ,the buttons are still not exclusive?

Thank you for your time


Solution

  • You're trying to add your JRadioButton variables to the ButtonGroup before you've created the radio button objects themselves, and in fact it looks as if you're trying to add nulls to the ButtonGroup.

    Solution: Don't do this. Create your JRadioButton objects first, and only then add them to the ButtonGroup.