mardi 12 février 2019

How to create a Radio Button that displays/removes a checkbox upon selection

I am trying to create a simple GUI application that has two radiobuttons and when the second one is selected it displays the checkbox, and if the first is selected it removes the checkbox

The issue I am having is that when the first radio button is selected (After choosing the second) it does not remove the checkbox, also the checkbox does not appear when selecting the second radiobutton until after resizing the window but this is not a big deal SimpleOutput.java

import javax.swing.JFrame;

public class SimpleOutput {

    public static void main(String[] args) {
        JFrame frame = new JFrame("Radio Check");
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

        frame.getContentPane().add(new StyleOptions());

        frame.pack();
        frame.setVisible(true);
    }

}

StyleOptions.java

import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.*;


public class StyleOptions extends JPanel {
    private JRadioButton RadioButton1, RadioButton2;
    private JCheckBox MyCheckBox;
    JPanel radiobuttonpanel = new JPanel();

    public StyleOptions() {
        setLayout(new BorderLayout());
        setBackground(Color.LIGHT_GRAY);

        RadioButton1 = new JRadioButton("RB1", true);
        RadioButton2 = new JRadioButton("RB2");
        RadioButton1.setVerticalAlignment(SwingConstants.CENTER);
        RadioButton2.setVerticalAlignment(SwingConstants.CENTER);

        MyCheckBox = new JCheckBox("My CheckBox");
        MyCheckBox.setVerticalAlignment(SwingConstants.CENTER);

        ButtonGroup group = new ButtonGroup();
        group.add(RadioButton1);
        group.add(RadioButton2);

        BoxLayout radiobuttonpanellayout = new BoxLayout(radiobuttonpanel, BoxLayout.Y_AXIS);
        radiobuttonpanel.setLayout(radiobuttonpanellayout);
        radiobuttonpanel.add(RadioButton1);
        radiobuttonpanel.add(RadioButton2);


        RadioListener listener = new RadioListener();
        RadioButton1.addActionListener(listener);
        RadioButton2.addActionListener(listener);
        MyCheckBox.addActionListener(listener);

        add(radiobuttonpanel);

    }

    private class RadioListener implements ActionListener {
        public void actionPerformed(ActionEvent event) {
            Object source = event.getSource();

            if (source == RadioButton1)
                System.out.println("RB1");
                radiobuttonpanel.remove(MyCheckBox);

            if (source == RadioButton2)
                System.out.println("RB2");
            radiobuttonpanel.add(MyCheckBox);

            if (MyCheckBox.isSelected())
                System.out.println("CheckBox!");
        }
    }
}

Thank you in advance




Aucun commentaire:

Enregistrer un commentaire