Adv Java - [Swing: JRadioButton Class]

♠ Posted by Unknown in at 20:43

JRadioButton Class



Radio buttons are supported by the JRadioButton class, which is a concrete implementation of AbstractButton.
Some of its constructors are show here:

     JRadioButton(Icon i)
     JRadioButton (Icon I, boolean state)
     JRadioButton (String s)
     JRadioButton (String s, boolean state)
     JRadioButton (String s, Icon i)
     JRadioButton (String s, Icon I, boolean state)

Radio buttons must be configured into a group. Only one of the buttons in that group is initially selected at any time. The ButtonGroup class is instantiated to create a button group. Its default constructor in invoked for this purpose. Elements are then added to the button group via the following method:
    
     void add(AbstractButton ab)


Radio button presses generate action events that are handled by actionPerformed(). The getActionCommand() method gets the text that is associated with a radio button and uses it to set text field.


Example:

/ *<APPLET CODE = "JRadioExample.CLASS" WIDTH = 500 HEIGHT = 500></APPLET>
 */
 import java.awt.*;
 import java.awt.event.*;
 import javax.swing.*;
public class JRadioExample extends JApplet implements ActionListener
{
          JTextField jtf;
          public void init()
          {
                   Container contentPane = getContentPane();
                   contentPane.setLayout(new FlowLayout());
                  
                   JRadioButton b1 = new JRadioButton("A");
                   b1.addActionListener(this);
                   contentPane.add(b1);
                  
                   JRadioButton b2 = new JRadioButton("B");
                   b2.addActionListener(this);
                   contentPane.add(b2);
                                     
                   JRadioButton b3 = new JRadioButton("C");
                   b3.addActionListener(this);
                   contentPane.add(b3);
                  
                   ButtonGroup bg = new ButtonGroup();
Image: Swing JRadioButton Example                   bg.add(b1);
                   bg.add(b2);
                   bg.add(b3);
                  
                   jtf = new JTextField(5);
                   contentPane.add(jtf);
          }
         
         
public void actionPerformed(ActionEvent ae)
          {
                   jtf.setText(ae.getActionCommand());
          }
}

0 comments:

Post a Comment