Free Data Structures and Algorithms Course









Subscribe below and get all best seller courses for free !!!










OR



Subscribe to all free courses

How to add Radio Buttons to a Swing frame in Java using JRadioButton class?

Program to demonstrate adding of a Radio Button to a Swing component in Java using JRadioButton class.

package com.hubberspot.awtSwing.example;

import java.awt.FlowLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;

import javax.swing.ButtonGroup;
import javax.swing.JFrame;
import javax.swing.JRadioButton;
import javax.swing.JTextField;
import javax.swing.SwingUtilities;

public class RadioButtonDemo extends JFrame {
  private JTextField textfield = new JTextField(16);
  private ButtonGroup groups = new ButtonGroup();
  private JRadioButton
  radiobutton1 = new JRadioButton("Java", false),
  radiobutton2 = new JRadioButton("C++", false),
  radiobutton3 = new JRadioButton("JavaScript", false);

  private ActionListener actionlistener = new ActionListener() {
    public void actionPerformed(ActionEvent event) {
  textfield.setText("I Like " +
  ((JRadioButton)event.getSource()).getText());
    }
  };

  public RadioButtonDemo() {
    radiobutton1.addActionListener(actionlistener);
    radiobutton2.addActionListener(actionlistener);
    radiobutton3.addActionListener(actionlistener);
    groups.add(radiobutton1); 
    groups.add(radiobutton2); 
    groups.add(radiobutton3);

    textfield.setEditable(false);

    setLayout(new FlowLayout());

    add(textfield);
    add(radiobutton1);
    add(radiobutton2);
    add(radiobutton3);
  }
  public static void main(String[] args) {
    setFrame(new RadioButtonDemo(), 225, 150);
  }

  public static void 
  setFrame(final JFrame frame, final int width, final int height) {
    SwingUtilities.invokeLater(new Runnable() {
       public void run() {
   frame.setTitle(frame.getClass().getSimpleName());
   frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
   frame.setSize(width, height);
   frame.setVisible(true);
 }
     });
  }

}

Output of the program : 








 
© 2021 Learn Java by Examples Template by Hubberspot