标签:set sys button pac container oid efault 添加 构造
示例:选择用户所喜欢的城市。
import java.awt.*; import java.awt.event.*; import javax.swing.*; public class JRadioButtonTest { JFrame f = null; JRadioButtonTest(){ f = new JFrame("单选框示例");//创建一个JFrame对象 Container contentPane = f.getContentPane();//创建一个内容面板容器 contentPane.setLayout(new FlowLayout());//设置该窗口布局 JPanel p1 = new JPanel(); //设置布局管理器格式 //p1.setLayout(new GridLayout(1,3));//这种是三个按钮在一行 p1.setLayout(new GridLayout(3,1));//这种是三个按钮在一列 p1.setBorder(BorderFactory.createTitledBorder("选择你喜欢的城市")); //定义3个JRadioButton单选按钮 JRadioButton r1 = new JRadioButton("北京"); JRadioButton r2 = new JRadioButton("上海"); JRadioButton r3= new JRadioButton("青岛"); p1.add(r1); p1.add(r2); p1.add(r3); r1.setSelected(true);//设置r1也就是”北京“按钮状态为选中 contentPane.add(p1);//面板对象p1加到窗口内容面板容器中 f.pack(); f.setVisible(true); f.addWindowListener(new WindowAdapter(){//添加窗口监听器 public void windowClosing(WindowEvent e){ System.exit(0); } }); } public static void main(String[] args) { // TODO Auto-generated method stub new JRadioButtonTest();//调用构造方法 } }
运行结果:
1.三个按钮在一行
2.三个按钮在一列
2.复选框(JCheckBox)
示例:一个继承面板favorite类,类别有:运动。电脑........
Favorite 类
import javax.swing.*; public class Favorite extends JPanel { JCheckBox sport,computer,music,read; Favorite(){ sport = new JCheckBox("运动"); computer = new JCheckBox("电脑"); music = new JCheckBox("音乐"); read = new JCheckBox("阅读"); add(new JLabel("爱好")); add(sport); add(computer); add(music); add(read); sport.setSelected(false); computer.setSelected(false); music.setSelected(false); read.setSelected(false); } }
JCheckBoxExample 类
import java.awt.*; import javax.swing.*; public class JCheckBoxExample extends JFrame { JCheckBoxExample(){ super("复选框"); Container container=getContentPane(); container.setLayout(new FlowLayout()); Favorite f=new Favorite(); container.add(f); pack(); setVisible(true); } public static void main(String[] args) { // TODO Auto-generated method stub JCheckBoxExample jcbe=new JCheckBoxExample(); jcbe.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); } }
运行结果:
标签:set sys button pac container oid efault 添加 构造
原文地址:https://www.cnblogs.com/sunblingbling/p/11946054.html