学习目标:
- 一个月掌握 Java 入门知识
学习内容:
- 按钮组件——单选按钮
- 按钮组件——复选框
1. 按钮组件——单选按钮
利用按钮组ButtonGroup实现单选操作。
import javax.swing.*;
import java.awt.*;
/**
* @author Vinyoo
* @date 2025/2/11 11:05
* 知识点:单选按钮
*/
public class TestJRadioButton {
public static void main(String[] args)
{
JFrame jFrame = new JFrame("这是一个JFrame窗体");
JRadioButton jRadioButton1 = new JRadioButton("按钮a");
JRadioButton jRadioButton2 = new JRadioButton("按钮b");
JRadioButton jRadioButton3 = new JRadioButton("按钮c");
//创建按钮组,若没有设置按钮组,则可实现多选,若设置了按钮组,则只能单选。
ButtonGroup buttonGroup = new ButtonGroup();
buttonGroup.add(jRadioButton1);
buttonGroup.add(jRadioButton2);
buttonGroup.add(jRadioButton3);
//添加到JFrame窗体中
jFrame.add(jRadioButton1);
jFrame.add(jRadioButton2);
jFrame.add(jRadioButton3);
jFrame.setLayout(new FlowLayout());
jFrame.setSize(300,300);
jFrame.setVisible(true);
jFrame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}
}
2. 按钮组件——复选框
利用JCheckBox类来创建。复选框可进行多选设置。
import javax.swing.*;
import java.awt.*;
/**
* @author Vinyoo
* @date 2025/2/11 11:19
* 知识点:复选框
*/
public class TestJCheckBox {
public static void main(String[] args)
{
JFrame jFrame = new JFrame("这是一个JFrame窗体");
jFrame.add(new JCheckBox("选项a"));
jFrame.add(new JCheckBox("选项b"));
jFrame.add(new JCheckBox("选项c"));
jFrame.setLayout(new FlowLayout());
jFrame.setSize(500,300);
jFrame.setVisible(true);
jFrame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}
}
与单选按钮的区别是:
(1)单选按钮是圈圈,复选框是框框。
(2)单选按钮选择后是圈中标黑点,复选框选择后是打勾且可多选。
代码部分注释写的很详细哦!试着练习一下吧!