单选按钮
构造ButtonGroup类型对象。
将JRadioButton对象添加到按钮组中。
new JRadioButton("Small",false),第二个参数是初始状态。
buttonGroup.getSelection().getActionCommand()获得当前选中的按钮动作命令。
选择字体大小案例
package swing;
import java.awt.BorderLayout;
import java.awt.Dimension;
import java.awt.Font;
import java.awt.Toolkit;
import java.awt.event.ActionListener;
import javax.swing.ButtonGroup;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JRadioButton;
public class RadioButtonTest {
private static final int DEFAULT_SIZE =36;
private static JPanel buttonPanel = new JPanel();
private static ButtonGroup buttonGroup = new ButtonGroup();
private static JLabel label = new JLabel("敏捷的棕色狐狸跳过懒惰的狗.");
public static void main(String[] args) {
JFrame frame = new JFrame("单选按钮");
label.setFont(new Font("Serif",Font.PLAIN,DEFAULT_SIZE));
frame.add(label,BorderLayout.CENTER);
addRadioButton("更小", 8);
addRadioButton("中等", 12);
addRadioButton("更大", 18);
addRadioButton("巨大", 36);
frame.add(buttonPanel,BorderLayout.SOUTH);
frame.setSize(600, 400);
//初始打开为屏幕中央
Toolkit toolkit = Toolkit.getDefaultToolkit();
Dimension screenSize = toolkit.getScreenSize();
int screenWidth = (int) screenSize.getWidth();
int screenHeight = (int) screenSize.getHeight();
//计算窗口位置
int x = (screenWidth - frame.getWidth())/2;
int y = (screenHeight - frame.getHeight())/2;
frame.setLocation(x, y);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setVisible(true);
}
public static void addRadioButton(String name,int size) {
boolean selected = size == DEFAULT_SIZE;
var button = new JRadioButton(name, selected);
buttonGroup.add(button);
buttonPanel.add(button);
ActionListener listener = e -> label.setFont(new Font("Serif", Font.PLAIN, size));
button.addActionListener(listener);
}
}