Search code examples
javaswingremovechildjradiobuttonbuttongroup

removing jRadioButton automatically in java


I have a set of JRadioButtons placed inside a JPanel. Also I have a "delete" button, such that if a JRadioButton is selected and then this "delete" button is pressed, the JRadioButton should be deleted from the JPanel.

I tried this following (action listener for the delete button) but it didn't work.

// bg: buttonGroup

private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {
    int count = -1;
    for (Enumeration e=bg.getElements(); e.hasMoreElements(); ) {
        JRadioButton b = (JRadioButton)e.nextElement();count++;
        if (b.getModel() == bg.getSelection()) {
            bg.remove(b);
            jPanel1.remove(jPanel1.getComponent(count)); 
        }
    }
}

Solution

  • Did you call

    jPanel1.revalidate();
    jPanel1.repaint();
    

    after deleting?