Tuesday 22 August 2017

Java Swing Radio Button Example | Swing Button Group | Java Swing Radio Button Only One Selected

                     In this post, we will see Java Swing Radio Button Example | Swing Button Group | Java Swing Radio Button Only One Selected. 

Watch following video:

                    To know what is Swing, how Swing is different from Applet, how to create Swing Application; check this post http://www.comrevo.com/2017/08/swing-in-java-with-example.html                    

                    To know how to generate event in Java Swing along with Java Swing program for addition of two numbers; check this post http://www.comrevo.com/2017/08/java-swing-program-for-addition-of-two-numbers.html 

                    Here, we will see Java Swing program for adding radio buttons on frame.  

                    In Swing, we can add radio buttons on frame by creating object of JRadioButton and by calling add() method.

                    The difference between checkboxes and radio buttons is that we can select multiple checkboxes while we can select only one radio button. To make such change in our program, we need to create a group of radio button out of which only one radio button can be selected. We can create group of radio button by creating object of class ButtonGroup and we need to call add() method. 

                    Go through the following program:


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

public class SwingRadio
   public static void main(String args[])
       Abc obj=new Abc();

class Abc extends JFrame implements ActionListener
  JLabel l1,l2,l3,l4;
  JTextField t1,t2;
  JButton b;
  JRadioButton r1,r2,r3;

  public Abc()
     setLayout(new FlowLayout());

     l1=new JLabel("Name:");
     t1=new JTextField(25); 
     l2=new JLabel("College:");
     t2=new JTextField(25);
     l3=new JLabel("Department:");

     r1=new JRadioButton("Computer Department");
     r2=new JRadioButton("Electronics Department");
     r3=new JRadioButton("IT Department");

     ButtonGroup bg=new ButtonGroup();

     b=new JButton("Submit");

     l4=new JLabel();




 public void actionPerformed(ActionEvent ae)
    String name=t1.getText();
    String college=t2.getText();
    String message;
       message="Welcome "+name+" To "+college+", "+r1.getText();
       message="Welcome "+name+" To "+college+","+r2.getText();
       message="Welcome "+name+" To "+college+","+r3.getText();


How To Run:
parag@parag-Inspiron-N4010:~/Desktop/prog$ javac SwingRadio.java 
parag@parag-Inspiron-N4010:~/Desktop/prog$ java SwingRadio


                        Check other posts on Java Programming in this link http://www.comrevo.com/2017/08/java-programming.html

No comments:

Post a Comment