Search code examples
javaswingnetbeansjradiobutton

Hide radio button on show jframe


I'm using netbeans 8. I have 2 radio button that I want to hide when the frame is shown. How can I do that? I successfully do that when I click other button such as this:

private void jRadioButton1ActionPerformed(java.awt.event.ActionEvent evt) {                                              
    // TODO add your handling code here:
    jRadioButton3.setVisible(false);
    jRadioButton4.setVisible(false);

}      

but that's not what I want. I want to set it to invisible and only show it when I click other radio button. For some reason netbean prevent me from editing certain area in my source code so I can't test or explore it. Please help and thanks in advance.


Solution

  • Set the JRadioButton setVisible method as false by default and then change it when an action is performed.

    For example, here under, the JRadioButtons will be visible once the first JRadioButton is selected. If it is deselected, they disappear.

    I did it with a JRadioButton but it can be done with other components of course.

    Solution

    public class Test extends JFrame{
    
        private JRadioButton but1, but2, but3;
    
        public Test(){
            setSize(new Dimension(200,200));
            initComp();
            setVisible(true);
        }
    
        private void initComp() {
            but1 = new JRadioButton();
            but1.addActionListener(new ActionListener(){
                @Override
                public void actionPerformed(ActionEvent e) {
                    but2.setVisible(but1.isSelected());
                    but3.setVisible(but1.isSelected());
                }
            });
    
            but2 = new JRadioButton();
            but2.setVisible(false);
    
            but3 = new JRadioButton();
            but3.setVisible(false);
            setLayout(new FlowLayout());
    
            JPanel pan = new JPanel();
            pan.add(but1);
            pan.add(but2);
            pan.add(but3);
    
            getContentPane().add(pan);
        }
    
        public static void main(String[] args) {
            new Test();
        }
    }