Search code examples
javaswingjradiobutton

program not returning proper results for RadioButton


When I run the code below, the first 2 buttons do not appear; however, the third one is visible in the frame.

public class RadioButton {
    RadioButton(){
        JFrame frame = new JFrame();
        JRadioButton button1 = new JRadioButton("One");
        button1.setBounds(50, 20, 50, 20);
        JRadioButton button2 = new JRadioButton("Two");
        button2.setBounds(50, 50, 50, 20);
        JRadioButton button3 = new JRadioButton("Three");
        button2.setBounds(50, 80, 50, 20);
        ButtonGroup bg  = new ButtonGroup();
        bg.add(button1);
        bg.add(button2);
        bg.add(button3);
        frame.add(button1);
        frame.add(button2);
        frame.add(button3);
        frame.setSize(300, 300);
        frame.setVisible(true);
        frame.setLayout(null);
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    }

    public static void main(String[] args) {
        new RadioButton();
    }

}

Solution

  • I guess since the OP set the layout manager to null, absolute positioning was what was wanted. This is not usually recommended. See the tutorial.

    You need to re-order the code as follows - i.e set the layout before setting the bounds of the components.

    public class RadioButton {
    
    RadioButton() {
        JFrame frame = new JFrame();
        JRadioButton button1 = new JRadioButton("One");
        JRadioButton button2 = new JRadioButton("Two");
        JRadioButton button3 = new JRadioButton("Three");
        ButtonGroup bg = new ButtonGroup();
        frame.setLayout(null);
        bg.add(button1);
        bg.add(button2);
        bg.add(button3);
        frame.setSize(300, 300);
        frame.add(button1);
        frame.add(button2);
        frame.add(button3);
        button1.setBounds(50, 20, 80, 20);
        button2.setBounds(50, 50, 80, 20);
        button3.setBounds(50, 80, 80, 20);
    
        SwingUtilities.invokeLater(new Runnable() {
    
            @Override
            public void run() {
                frame.setVisible(true);
            }
        });
    
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    }
    
    public static void main(String[] args) {
        new RadioButton();
    }
    }
    

    I am using OS X and I needed to make the buttons a bit bigger to avoid their captions being displayed as '...'. Finally I used invokeLater, which IIRC is best practice.