Java: Can Radio Buttons of the same Button Group be in different Panels?

521 views Asked by At

I already added the radio buttons to the button group but the problem is that both the radio buttons can be selected at the same time! I don't know what to do. Please help. This is how my current code looks like:

JRadioButton rEncrypt, rDecrypt;

ButtonGroup bgroup = new ButtonGroup();
bgroup.add(rEncrypt);   bgroup.add(rDecrypt);


    rEncrypt = new JRadioButton("Encryption");
    rEncrypt.setBackground(bgColor);
    rEncrypt.setSelected(true);
    pEncrypt = new JPanel();
    pEncrypt.setBackground(bgColor);
    pEncrypt.add(rEncrypt);


    rDecrypt = new JRadioButton("Decryption");
    rDecrypt.setBackground(bgColor);
    pDecrypt = new JPanel();
    pDecrypt.setBackground(bgColor);
    pDecrypt.add(rDecrypt);
1

There are 1 answers

0
MadProgrammer On

Without seeing a fully runnable example...

Doing this...

JRadioButton rEncrypt, rDecrypt;

ButtonGroup bgroup = new ButtonGroup();
bgroup.add(rEncrypt);   bgroup.add(rDecrypt);

before this...

rEncrypt = new JRadioButton("Encryption");
//...
rDecrypt = new JRadioButton("Decryption");

is wrong...

You need to create the buttons BEFORE you add them to the ButtonGroup...