JRadioButton | Columpio Java

Usamos la clase JRadioButton para crear un botón de opción. El botón de radio se usa para seleccionar una opción de múltiples opciones. Se utiliza para completar formularios, documentos objetivos en línea y cuestionarios.

Agregamos botones de radio en un ButtonGroup para que podamos seleccionar solo un botón de radio a la vez. Usamos la clase «ButtonGroup» para crear un ButtonGroup y agregar un botón de opción en un grupo.

Métodos utilizados:

  1. JRadioButton() : Crea un RadioButton no seleccionado sin texto.
    Ejemplo:
    JRadioButton j1 = new JRadioButton() 
    
  2. JButton(String s) : Crea un JButton con un texto específico.
    Ejemplo:
    JButton b1 = new JButton("Button") 
    
  3. JLabel(String s) : Crea una JLabel con un texto específico.
    Ejemplo:
    JLabel L = new JLabel("Label 1") 
    
  4. ButtonGroup() : Úselo para crear un grupo, en el que podemos agregar JRadioButton. Podemos seleccionar solo un JRadioButton en un ButtonGroup.
    Pasos para agrupar los botones de opción.
    • Cree una instancia de ButtonGroup utilizando el método «ButtonGroup()».
      ButtonGroup G = new ButtonGroup()
      
    • Ahora agregue botones en un Grupo «G», con la ayuda del Método «add()».

      Ejemplo:

      G.add(Button1);
      G.add(Button2);
      
  5. isSelected() : devolverá un valor booleano verdadero o falso, si se selecciona un JRadioButton devolverá verdadero de lo contrario falso.

    Ejemplo:

    JRadioButton.isSelected()
    
  6. Métodos Set(…) y Get(…):
    i) Set y get se utilizan para reemplazar las variables miembro de acceso directo desde clases externas.

    ii) En lugar de acceder directamente a las variables de los miembros de la clase, define obtener métodos para acceder a estas variables y establece métodos para modificarlas.

La descripción de algunas funciones utilizadas en el programa se proporciona en este enlace: Funciones Descripción

Programa 1: JRadioButton sin ActionListener

// Java program to show JRadioButton Example.
// in java. Importing different Package.
import java.awt.*;
import javax.swing.*;
import java.awt.event.*;
  
class Demo extends JFrame {
  
    // Declaration of object of JRadioButton class.
    JRadioButton jRadioButton1;
  
    // Declaration of object of JRadioButton class.
    JRadioButton jRadioButton2;
  
    // Declaration of object of JButton class.
    JButton jButton;
  
    // Declaration of object of ButtonGroup class.
    ButtonGroup G1;
  
    // Declaration of object of  JLabel  class.
    JLabel L1;
  
    // Constructor of Demo class.
    public Demo()
    {
  
        // Setting layout as null of JFrame.
        this.setLayout(null);
  
        // Initialization of object of "JRadioButton" class.
        jRadioButton1 = new JRadioButton();
  
        // Initialization of object of "JRadioButton" class.
        jRadioButton2 = new JRadioButton();
  
        // Initialization of object of "JButton" class.
        jButton = new JButton("Click");
  
        // Initialization of object of "ButtonGroup" class.
        G1 = new ButtonGroup();
  
        // Initialization of object of " JLabel" class.
        L1 = new JLabel("Qualification");
  
        // setText(...) function is used to set text of radio button.
        // Setting text of "jRadioButton2".
        jRadioButton1.setText("Under-Graduate");
  
        // Setting text of "jRadioButton4".
        jRadioButton2.setText("Graduate");
  
        // Setting Bounds of "jRadioButton2".
        jRadioButton1.setBounds(120, 30, 120, 50);
  
        // Setting Bounds of "jRadioButton4".
        jRadioButton2.setBounds(250, 30, 80, 50);
  
        // Setting Bounds of "jButton".
        jButton.setBounds(125, 90, 80, 30);
  
        // Setting Bounds of JLabel "L2".
        L1.setBounds(20, 30, 150, 50);
  
        // "this" keyword in java refers to current object.
        // Adding "jRadioButton2" on JFrame.
        this.add(jRadioButton1);
  
        // Adding "jRadioButton4" on JFrame.
        this.add(jRadioButton2);
  
        // Adding "jButton" on JFrame.
        this.add(jButton);
  
        // Adding JLabel "L2" on JFrame.
        this.add(L1);
  
        // Adding "jRadioButton1" and "jRadioButton3" in a Button Group "G2".
        G1.add(jRadioButton1);
        G1.add(jRadioButton2);
    }
}
  
class RadioButton {
    // Driver code.
    public static void main(String args[])
    { // Creating object of demo class.
        Demo f = new Demo();
  
        // Setting Bounds of JFrame.
        f.setBounds(100, 100, 400, 200);
  
        // Setting Title of frame.
        f.setTitle("RadioButtons");
  
        // Setting Visible status of frame as true.
        f.setVisible(true);
    }
}

Producción:


Programa 2: JRadioButton con ActionListener

// Java program to show JRadioButton Example.
// in java. Importing different Package.
import java.awt.*;
import javax.swing.*;
import java.awt.event.*;
  
class Demo extends JFrame {
  
    // Declaration of object of JRadioButton class.
    JRadioButton jRadioButton1;
  
    // Declaration of object of JRadioButton class.
    JRadioButton jRadioButton2;
  
    // Declaration of object of JButton class.
    JButton jButton;
  
    // Declaration of object of ButtonGroup class.
    ButtonGroup G1;
  
    // Declaration of object of  JLabel  class.
    JLabel L1;
  
    // Constructor of Demo class.
    public Demo()
    {
  
        // Setting layout as null of JFrame.
        this.setLayout(null);
  
        // Initialization of object of "JRadioButton" class.
        jRadioButton1 = new JRadioButton();
  
        // Initialization of object of "JRadioButton" class.
        jRadioButton2 = new JRadioButton();
  
        // Initialization of object of "JButton" class.
        jButton = new JButton("Click");
  
        // Initialization of object of "ButtonGroup" class.
        G1 = new ButtonGroup();
  
        // Initialization of object of " JLabel" class.
        L1 = new JLabel("Qualification");
  
        // setText(...) function is used to set text of radio button.
        // Setting text of "jRadioButton2".
        jRadioButton1.setText("Under-Graduate");
  
        // Setting text of "jRadioButton4".
        jRadioButton2.setText("Graduate");
  
        // Setting Bounds of "jRadioButton2".
        jRadioButton1.setBounds(120, 30, 120, 50);
  
        // Setting Bounds of "jRadioButton4".
        jRadioButton2.setBounds(250, 30, 80, 50);
  
        // Setting Bounds of "jButton".
        jButton.setBounds(125, 90, 80, 30);
  
        // Setting Bounds of JLabel "L2".
        L1.setBounds(20, 30, 150, 50);
  
        // "this" keyword in java refers to current object.
        // Adding "jRadioButton2" on JFrame.
        this.add(jRadioButton1);
  
        // Adding "jRadioButton4" on JFrame.
        this.add(jRadioButton2);
  
        // Adding "jButton" on JFrame.
        this.add(jButton);
  
        // Adding JLabel "L2" on JFrame.
        this.add(L1);
  
        // Adding "jRadioButton1" and "jRadioButton3" in a Button Group "G2".
        G1.add(jRadioButton1);
        G1.add(jRadioButton2);
  
        // Adding Listener to JButton.
        jButton.addActionListener(new ActionListener() {
            // Anonymous class.
  
            public void actionPerformed(ActionEvent e)
            {
                // Override Method
  
                // Declaration of String class Objects.
                String qual = " ";
  
                // If condition to check if jRadioButton2 is selected.
                if (jRadioButton1.isSelected()) {
  
                    qual = "Under-Graduate";
                }
  
                else if (jRadioButton2.isSelected()) {
  
                    qual = "Graduate";
                }
                else {
  
                    qual = "NO Button selected";
                }
  
                // MessageDialog to show information selected radio buttons.
                JOptionPane.showMessageDialog(Demo.this, qual);
            }
        });
    }
}
  
class RadioButton {
    // Driver code.
    public static void main(String args[])
    { // Creating object of demo class.
        Demo f = new Demo();
  
        // Setting Bounds of JFrame.
        f.setBounds(100, 100, 400, 200);
  
        // Setting Title of frame.
        f.setTitle("RadioButtons");
  
        // Setting Visible status of frame as true.
        f.setVisible(true);
    }
}

Producción:


Después de presionar el botón «clic».


Programa 3 Programa para crear un grupo simple de botones de radio (con imagen) y agregarles un detector de elementos

// Java Program to create a simple group of radio buttons 
// (with image )and add item listener to them
import java.awt.event.*;
import java.awt.*;
import javax.swing.*;
class solve extends JFrame implements ItemListener {
  
    // frame
    static JFrame f;
  
    // radiobuttons
    static JRadioButton b, b1;
  
    // create a label
    static JLabel l1;
  
    // main class
    public static void main(String[] args)
    {
        // create a new frame
        f = new JFrame("frame");
  
        // create a object
        solve s = new solve();
  
        // create a panel
        JPanel p = new JPanel();
  
        // create a new label
        JLabel l = new JLabel("which website do you like?");
        l1 = new JLabel("geeksforgeeks selected");
  
        // create Radio buttons
        b = new JRadioButton("geeksforgeeks", new ImageIcon("f:/gfg.jpg"));
        b1 = new JRadioButton("others");
  
        // create a button group
        ButtonGroup bg = new ButtonGroup();
  
        // add item listener
        b.addItemListener(s);
        b1.addItemListener(s);
  
        // add radio buttons to button group
        bg.add(b);
        bg.add(b1);
  
        b.setSelected(true);
  
        // add button and label to panel
        p.add(l);
        p.add(b);
        p.add(b1);
        p.add(l1);
  
        f.add(p);
  
        // set the size of frame
        f.setSize(400, 400);
  
        f.show();
    }
  
    public void itemStateChanged(ItemEvent e)
    {
        if (e.getSource() == b) {
            if (e.getStateChange() == 1) {
                l1.setText("geeksforgeeks selected");
            }
        }
        else {
  
            if (e.getStateChange() == 1) {
                l1.setText("others selected");
            }
        }
    }
}

Producción :

Nota: Es posible que los siguientes programas no se ejecuten en un compilador en línea; utilice un IDE sin conexión.

Publicación traducida automáticamente

Artículo escrito por Amaninder.Singh y traducido por Barcelona Geeks. The original can be accessed here. Licence: CCBY-SA

Deja una respuesta

Tu dirección de correo electrónico no será publicada. Los campos obligatorios están marcados con *