1、第一步,打开MyEclipse开发工具,在Web项目指定目录下创建Java类RadioButton,并继承JFrame,如下图所示:
2、第二步,声明一个JFrame、一个JPanel和四个JRadioButtonprivate JFrame frame = new JFrame(); //面板 private JPanel panel = new JPanel(); //单选按钮一 private JRadioButton radioOne = new JRadioButton(); //单选按钮二 private JRadioButton radioTwo = new JRadioButton(); //单选按钮三 private JRadioButton radioThree = new JRadioButton(); //单选按钮四 private JRadioButton radioFour = new JRadioButton();如下图所示:
3、第三步,新建RadioButton构造函数,并设置JFrame样式、关闭方式frame.setBackground(Color.WHITE); frame.setBounds(50, 50, 600, 400); frame.setFont(new Font("黑体", Font.BOLD, 20)); frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); frame.setCursor(Cursor.HAND_CURSOR); frame.setVisible(true);如下图所示:
4、第四步,设置JPanel范围、背景色、布局、可见性和鼠标样式panel.setBounds(10, 10, 300, 200); panel.setBackground(Color.BLACK); panel.setVisible(true); panel.setEnabled(true); panel.setLayout(new FlowLayout(FlowLayout.CENTER, 6, 6)); setContentPane(panel);如下图所示:
5、第五步,给四个单选按钮JRadioButton添加内容,并加到JPanel上radioOne.setText烫喇霰嘴("春季"); radioOne.setEnabled(true); radioTwo.setText("夏季"); radioTwo.setEnabled(true); radioThree.setText("秋季"); radioThree.setEnabled(true); radioFour.setText("冬季"); radioFour.setEnabled(true); panel.add(radioOne); panel.add(radioTwo); panel.add(radioThree); panel.add(radioFour);如下图所示:
6、第六步,声明一个ButtonGroup,这个组件控制JRadioButton单选,ButtonGroup button = new ButtonGroup(); button.add(radioOne); button.add(radioTwo); button.add(radioThree); button.add(radioFour); frame.add(panel);如下图所示: