【java入门】初学者常用窗口Swing控件整理 ;
身为初学者,不得不被java强大的库和方法所征服,刚刚学习了解了有关JAVA窗口编程的控件,现于此整理一下以备忘。
private JFrame jfrmMainFrame;
private Container container;
定义一个”容器“,允许程序员把其他组件(Swing 的三个基本构造块:标签、按钮和文本字段)添加到它里面,把它们组织起 来,并把它们呈现给用户。
容器
private JLabel JlblTopic;
定义一个标签:标题,文字,等等
private JTextField jtxtName;
定义一个文本框:例 姓名
private JRadioButton jrdbSexGG;
定义一个选择按钮:性别GG
private ButtonGroup btgpSex;
定义一个”按钮组“
可通过按钮组的add方法,将几个属性相同的按钮加到同一个组里,实现只能选择一个
private JButton button;
定义一个按钮;
private JPasswordField jtxtPassword;
定义一个密码文本框
private JComboBox<String> jcmbBirthdayYear;
定义一个下拉菜单
private JPanel jpnlHobbies;
定义一个面板容器
private JScrollPane jscpUserList;
滚动面板
字体和颜色设置("字体名",字体样式,字体大小)
Font topicFont = new Font("幼圆", Font.BOLD, 38);
Color topicColor = new Color(0, 64, 128);
构建出一个自己的窗口
jfrmMaiame = new JFrame("我的第一个窗口");
container = jfrmMainFrame.getContentPane();
container.setLayout(null);
设置主窗口属性
jfrmMainFrame.setSize(窗口宽, 窗口高);
//窗口位置,null为默认居中
jfrmMainFrame.setLocationRelativeTo(null);
//设置窗口右上角×功能,我在这里设置为退出
jfrmMainFrame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
设置标签
//位置设为居中
JlblTopic = new JLabel("名称",JLabel.CENTER);
// 设置标题字体
lblTopic.setFont(自己前面设置的字体);
// 设置标题颜色
JlblTopic.setForeground(自己前面设置的颜色);
// 标签位置
// 括号里依次是距 左边距离,距上边距离,字 体宽,字体高
// 因为已定义位置居中,所以第一个参数设置为0,则居中
JlblTopic.setBounds(0, 0, mainWidth, topicFont.getSize());
// 将标签加入到”容器里“;否则无法显示
container.add(JlblTopic);
文本框 和 密码框 设置
// 生成文本框
jtxtName = new JTextField();
jtxtName.setFont(字体); //文本框字体,参照标题字体设置
jtxtName.setBounds(距左位置, 距上位置, 文本框宽度, 文本框高);
container.add(jtxtName);
// 生成密码框
jtxtPassword = new JPasswordField();
jtxtPassword.setFont(字体; //密码框字体,参照标题字体设置
jtxtPassword.setBounds(距左位置, 距上位置, 密码框宽度, 密码框高);
jtxtPassword.setEchoChar('*'); //设置字符样式
container.add(jpswPassword);
单选按钮 设置示例
jrdbSexGG = new JRadioButton("男");
jrdbSexGG.setFont(字体);
jrdbSexGG.setSelected(true); //设置按钮开始属性,已选
jrdbSexGG.setBounds(距左位置, 距上位置, 按钮框宽度, 按钮框高);
container.add(jrdbGG);
若要将其两个或以上的按钮设置为只能选择一个,则需要将其放入一个”按钮组“里
btgpSex = new ButtonGroup();
btgpSex.add(jrdbSexGG);
。。。。
下拉盒子 设置
jcmbBirthdayYear = new JComboBox<String>();
jcmbBirthdayYear.setFont(字体);
jcmbBirthdayYear.setBounds(距左位置, 距上位置, 宽, 高);
container.add(jcmbBirthdayYear);