Friday, 8 February 2013

Get Selected JRadioButton From ButtonGroup

Hai friends now i am going to share how we can get selected JRadioButton from ButtonGroup..

























GettingRadioButtonValueTwo.java


import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.Enumeration;

import javax.swing.AbstractButton;
import javax.swing.ButtonGroup;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JRadioButton;


public class GettingRadioButtonValueTwo implements ActionListener {
 JRadioButton rb1 =new JRadioButton("Sarathi");
 JRadioButton rb2=new JRadioButton("Bishop");
 JFrame f=new JFrame("Radio Button Example");
 JPanel p=new JPanel();
 JLabel l=new JLabel("Answer");
 JButton b=new JButton("Submit");
 ButtonGroup bg=new ButtonGroup();
 
 public void init()
 {
  bg.add(rb1);
  bg.add(rb2);
  p.add(rb1);
  p.add(rb2);
  p.add(b);
  p.add(l);
  f.add(p);
  f.setSize(500, 500);
  f.setVisible(true);
  b.addActionListener(this);
 }
 public static void main(String args[])
 {
  GettingRadioButtonValueTwo gr=new GettingRadioButtonValueTwo();
  gr.init();
 }
 @Override
 public void actionPerformed(ActionEvent arg0) {
  // TODO Auto-generated method stub
  String ss="";
  Enumeration e=bg.getElements();
  while(e.hasMoreElements())
  {
   JRadioButton r=(JRadioButton)e.nextElement();
   if(r.isSelected())
   {
    ss=r.getText();
   }
  }
  l.setText(ss);
  
 }

  
}



Thanks for Visiting
 -- 
Regards with

R. Partha Sarathy

No comments:

Post a Comment