Advertisement
RupeshAcharya60

JRadio Button with Java Swing

Mar 24th, 2023 (edited)
552
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 1.29 KB | Source Code | 0 0
  1. import javax.swing.*;
  2. import java.awt.*;
  3. import java.awt.event.*;
  4.  
  5.  class RadioButtonExample extends JFrame {
  6.     public RadioButtonExample() {
  7.         setTitle("Radio Button Example");
  8.         setSize(300, 200);
  9.         setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
  10.  
  11.         JPanel panel = new JPanel();
  12.         add(panel);
  13.  
  14.         ButtonGroup group = new ButtonGroup();
  15.  
  16.         JRadioButton radio1 = new JRadioButton("Option 1");
  17.         group.add(radio1);
  18.         panel.add(radio1);
  19.  
  20.         JRadioButton radio2 = new JRadioButton("Option 2");
  21.         group.add(radio2);
  22.         panel.add(radio2);
  23.  
  24.         JRadioButton radio3 = new JRadioButton("Option 3");
  25.         group.add(radio3);
  26.         panel.add(radio3);
  27.  
  28.         ActionListener listener = new ActionListener() {
  29.             public void actionPerformed(ActionEvent e) {
  30.                 System.out.println("Selected option: " + ((JRadioButton)e.getSource()).getText());
  31.             }
  32.         };
  33.  
  34.         radio1.addActionListener(listener);
  35.         radio2.addActionListener(listener);
  36.         radio3.addActionListener(listener);
  37.     }
  38.  
  39.  
  40. }
  41.  
  42.  
  43. public class GUI{
  44.     public static void main(String[] args) {
  45.         RadioButtonExample example = new RadioButtonExample();
  46.         example.setVisible(true);
  47.     }
  48. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement