Page 217 - CTS - CSA TP - Volume 2
P. 217

COMPUTER SOFTWARE APPLICATION - CITS




           4  Frame Initialization:
              JFrame frame = new JFrame(“RadioButton Example”);
              Create a JFrame (window) with the title “RadioButton Example”.
           5  RadioButton Creation:

              JRadioButton  radioButton1  = new  JRadioButton(“Male”); JRadioButton  radioButton2  = new
              JRadioButton(“Female”);
              Create two JRadioButton instances with labels “Male” and “Female”.
           6  ButtonGroup Setup:

              ButtonGroup group = new ButtonGroup();
               group.add(radioButton1);
              group.add(radioButton2);
              Create a ButtonGroup and add the radio buttons to it. This ensures that only one radio button in the group can
              be selected at a time.
           7  Submit Button Creation:
              JButton submitButton = new JButton(“Submit”);

              Create a JButton with the label “Submit”.
           8  ActionListener for Submit Button:
              submitButton.addActionListener(new ActionListener()
              { @Override public void actionPerformed(ActionEvent e)
               { String selectedOption = radioButton1.isSelected() ? “Male” : “Female”; JOptionPane.showMessageDialog(frame,
              “Selected Option: “ + selectedOption); } });
              Attach an ActionListener to the submit button. When the button is clicked, it checks which radio button is
              selected and displays a message dialog accordingly.
           9  Frame Layout and Components Addition:
              frame.setLayout(new BoxLayout(frame.getContentPane(),  BoxLayout.Y_AXIS)); frame.getContentPane().
              add(radioButton1); frame.getContentPane().add(radioButton2); frame.getContentPane().add(submitButton);

              Set the layout of the frame to a vertical box layout and add the radio buttons and the submit button to the
              content pane of the frame.
           10 Frame Configuration and Display:

              frame.setSize(300, 200); frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); frame.setVisible(true);
              Set the size, default close operation, and make the frame visible.
              This program creates a simple GUI with two radio buttons and a submit button. Upon clicking the submit
              button, a message dialog is shown, indicating the selected gender. The use of ButtonGroup ensures exclusive
              selection.




















                                                           202

                              CITS : IT & ITES - Computer Software Application - Exercise 117                                                        CITS : IT & ITES - Computer Software Application - Exercise 117
   212   213   214   215   216   217   218   219   220   221   222