📄 radiobuttonexample.java
字号:
//RadioButtonExample.java
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import javax.swing.event.*;
public class RadioButtonExample
{
public static void main(String[] args)
{
RadioButtonFrame frame = new RadioButtonFrame();
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.show();
}
}
class RadioButtonFrame extends JFrame
{
public RadioButtonFrame()
{
setTitle("RadioButtonExample");
setSize(WIDTH, HEIGHT);
Container contentPane = getContentPane();
//新建标签
myLabel = new JLabel("Origin choice: EAST", JLabel.CENTER);
contentPane.add(myLabel, BorderLayout.CENTER);
//建立容器面板
radioPanel = new JPanel();
//新建单选按钮
myButtonGroup = new ButtonGroup();
addRadioButton("EAST" , true, "EAST");
addRadioButton("SOUTH" , false, "SOUTH");
addRadioButton("WEST" , false, "WEST");
addRadioButton("NORTH" , false, "NORTH");
contentPane.add(radioPanel, BorderLayout.SOUTH);
}
//将单选按钮加入到按钮组中
public void addRadioButton(String name, boolean defaultRadio, String show)
{
final String showLabel = show;
JRadioButton button = new JRadioButton(name, defaultRadio);
myButtonGroup.add(button);
radioPanel.add(button);
//添加事件监听器
button.addActionListener(new ActionListener()
{
public void actionPerformed(ActionEvent evt)
{
myLabel.setText("You choosed: " + showLabel);
}
});
}
public static final int WIDTH = 300;
public static final int HEIGHT = 140;
private JLabel myLabel;
private ButtonGroup myButtonGroup;
private JPanel radioPanel;
}
⌨️ 快捷键说明
复制代码
Ctrl + C
搜索代码
Ctrl + F
全屏模式
F11
切换主题
Ctrl + Shift + D
显示快捷键
?
增大字号
Ctrl + =
减小字号
Ctrl + -