📜  Java Swing-JRadioButton

📅  最后修改于: 2020-09-30 05:56:32             🧑  作者: Mango

Java JRadioButton

JRadioButton类用于创建单选按钮。它用于从多个选项中选择一个选项。它广泛用于考试系统或测验中。

应该将其添加到ButtonGroup中,以仅选择一个单选按钮。

JRadioButton类声明

让我们看看javax.swing.JRadioButton类的声明。

public class JRadioButton extends JToggleButton implements Accessible

常用的构造函数:

Constructor Description
JRadioButton() Creates an unselected radio button with no text.
JRadioButton(String s) Creates an unselected radio button with specified text.
JRadioButton(String s, boolean selected) Creates a radio button with the specified text and selected status.

常用方法:

Methods Description
void setText(String s) It is used to set specified text on button.
String getText() It is used to return the text of the button.
void setEnabled(boolean b) It is used to enable or disable the button.
void setIcon(Icon b) It is used to set the specified Icon on the button.
Icon getIcon() It is used to get the Icon of the button.
void setMnemonic(int a) It is used to set the mnemonic on the button.
void addActionListener(ActionListener a) It is used to add the action listener to this object.

Java JRadioButton示例

import javax.swing.*;  
public class RadioButtonExample {  
JFrame f;  
RadioButtonExample(){  
f=new JFrame();   
JRadioButton r1=new JRadioButton("A) Male");  
JRadioButton r2=new JRadioButton("B) Female");  
r1.setBounds(75,50,100,30);  
r2.setBounds(75,100,100,30);  
ButtonGroup bg=new ButtonGroup();  
bg.add(r1);bg.add(r2);  
f.add(r1);f.add(r2);    
f.setSize(300,300);  
f.setLayout(null);  
f.setVisible(true);  
}  
public static void main(String[] args) {  
    new RadioButtonExample();  
}  
}  

输出:

带有ActionListener的Java JRadioButton示例

import javax.swing.*;  
import java.awt.event.*;  
class RadioButtonExample extends JFrame implements ActionListener{  
JRadioButton rb1,rb2;  
JButton b;  
RadioButtonExample(){    
rb1=new JRadioButton("Male");  
rb1.setBounds(100,50,100,30);    
rb2=new JRadioButton("Female");  
rb2.setBounds(100,100,100,30);  
ButtonGroup bg=new ButtonGroup();  
bg.add(rb1);bg.add(rb2);  
b=new JButton("click");  
b.setBounds(100,150,80,30);  
b.addActionListener(this);  
add(rb1);add(rb2);add(b);  
setSize(300,300);  
setLayout(null);  
setVisible(true);  
}  
public void actionPerformed(ActionEvent e){  
if(rb1.isSelected()){  
JOptionPane.showMessageDialog(this,"You are Male.");  
}  
if(rb2.isSelected()){  
JOptionPane.showMessageDialog(this,"You are Female.");  
}  
}  
public static void main(String args[]){  
new RadioButtonExample();  
}} 

输出: