📜  Java Swing-JRadioButton(1)

📅  最后修改于: 2023-12-03 15:01:32.549000             🧑  作者: Mango

Java Swing - JRadioButton

Introduction

JRadioButton is a Swing component which allows the user to choose one option from a group of options. It is a part of the javax.swing package and is typically used in forms, quizzes, and other similar applications where a user is required to make a choice from a set of options.

Features
  • JRadioButton extends AbstractButton and inherits its features.
  • JRadioButton has a label associated with it that is displayed to the user.
  • JRadioButton can be selected or deselected by the user.
  • JRadioButton comes in a group, which allows the user to select only one option at a time.
  • JRadioButton can be customized by changing its appearance, size, color, and other properties.
Code Example

Below is an example of how to create a basic JRadioButton in Java:

import javax.swing.*;
import java.awt.*;
 
public class JRadioButtonExample extends JFrame {
 
  private JRadioButton radioButton1;
  private JRadioButton radioButton2;
  private ButtonGroup radioGroup;
 
  public JRadioButtonExample() {
 
    // Set the frame properties
    setTitle("JRadioButton Example");
    setSize(300, 200);
    setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
 
    // Create the radio buttons and group
    radioButton1 = new JRadioButton("Option 1");
    radioButton2 = new JRadioButton("Option 2");
    radioGroup = new ButtonGroup();
 
    // Add the radio buttons to the group
    radioGroup.add(radioButton1);
    radioGroup.add(radioButton2);
 
    // Add the radio buttons to the frame
    setLayout(new GridLayout(3, 1));
    add(new JLabel("Choose an option:"));
    add(radioButton1);
    add(radioButton2);
 
    // Show the frame
    setVisible(true);
  }
 
  public static void main(String[] args) {
    JRadioButtonExample example = new JRadioButtonExample();
  }
}
Conclusion

JRadioButton is a versatile Swing component that can be used to provide users with a visually intuitive way of making a choice between different options. It is easy to use and highly customizable, making it a popular choice for developers working on various types of applications.