在本例演示了JTextField,JTextArea,JPasswordField,JCheckBox(复选框按钮),JRadioButton(下拉列表框组件),JLabel等基本组件的用法。
需要注意的是:若多个JRadioButton需要归为一组时,需要把这些JRadioButton使用add()方法添加到ButtonGroup中对象。
import java.awt.*;import java.awt.event.*;import javax.swing.*;public class TestRegister extends JFrame { private static final long serialVersionUID = 1L; JLabel uname,passwd,confpasswd,sex,utype,like,introduce; JPasswordField pf1,pf2; JButton submit,reset; JTextField tf; JTextArea intro; JCheckBox reading,writing,chatting; JRadioButton m,f; JComboBox cb; TestRegister(String name) { super(name); this.setVisible(true); this.setBounds(400,300,400,400); this.setLayout(new GridLayout(8,2)); this.addWindowListener(new WindowAdapter() { public void windowClosing(WindowEvent e) { System.exit(0); } }); } public void init() { uname = new JLabel("用户名"); passwd = new JLabel("密码"); confpasswd = new JLabel("确认密码"); sex = new JLabel("性别"); utype = new JLabel("用户类别"); like = new JLabel("爱好"); introduce = new JLabel("简介"); pf1 = new JPasswordField(10); pf2 = new JPasswordField(10); submit = new JButton("提交"); reset = new JButton("重置"); tf = new JTextField(10); intro = new JTextArea(3,10); reading = new JCheckBox("Reading"); writing = new JCheckBox("Writing"); chatting = new JCheckBox("Chatting"); m = new JRadioButton("男"); f = new JRadioButton("女"); cb = new JComboBox(); cb.addItem("管理员"); cb.addItem("会员"); cb.addItem("游客"); ButtonGroup bg = new ButtonGroup(); bg.add(m); bg.add(f); JPanel p1 = new JPanel(); p1.add(m); p1.add(f); JPanel p2 = new JPanel(); p2.add(reading); p2.add(writing); p2.add(chatting); JPanel p3 = new JPanel(); JPanel p4 = new JPanel(); p3.add(submit); p4.add(reset); this.add(uname); this.add(tf); this.add(passwd); this.add(pf1); this.add(confpasswd); this.add(pf2); this.add(sex); this.add(p1); this.add(utype); this.add(cb); this.add(like); this.add(p2); this.add(introduce); this.add(intro); this.add(p3); this.add(p4); this.pack(); } public static void main(String[] args) { new TestRegister("user Register").init(); }}
运行结果: