importjava.awt.event.ActionEvent;importjava.awt.event.ActionListener;importjavax.swing.JButton;importjavax.swing.JLabel;importjavax.swing.JPanel;importjavax.swing.JTextField;importjavax.swing.JTextPane;public class ComponentDemo extends JPanel implementsActionListener {//JLabel是标签,JTextField是文本框
private JLabel userLabel = null;private JTextField userText = null;private JLabel passwordLabel = null;private JTextField passwordText = null;private JButton btnLogin = null;private JLabel contentLabel = null;private JTextPane contentPane = null;//组件初始化
publicComponentDemo() {super();
initialize();
}private voidinitialize() {
userLabel= newJLabel();/*用setBounds(Rectangle r)画矩形,Rectangle(x,y,weight,height)
x,y表示矩形的左上角坐标,weight表示矩形长度,height表示高度*/userLabel.setBounds(new java.awt.Rectangle(10, 10, 70, 22));
userLabel.setText("账号:");this.setLayout(null);//添加Label(标签)和TextField(文本框)
this.add(userLabel, null);this.add(getUserText(), null);this.add(getPasswordLabel(), null);this.add(getPasswordText(), null);this.add(getBtnLogin(), null);this.add(getContentLabel(), null);this.add(getContentPaneText(), null);
}privateJTextField getUserText() {if (userText == null) {
userText= newJTextField();
userText.setBounds(new java.awt.Rectangle(80, 10, 100, 22));
}returnuserText;
}privateJLabel getPasswordLabel() {if (passwordLabel == null) {
passwordLabel= newJLabel();
passwordLabel.setText("密码:");
passwordLabel.setBounds(new java.awt.Rectangle(210, 10, 70, 22));
}returnpasswordLabel;
}privateJTextField getPasswordText() {if (passwordText == null) {
passwordText= newJTextField();
passwordText.setBounds(new java.awt.Rectangle(280, 10, 100, 22));
}returnpasswordText;
}privateJLabel getContentLabel() {if (contentLabel == null) {
contentLabel= newJLabel();
contentLabel.setText("内容如下:");
contentLabel.setBounds(new java.awt.Rectangle(10, 70, 70, 22));
}returncontentLabel;
}privateJTextPane getContentPaneText() {if (contentPane == null) {
contentPane= newJTextPane();
contentPane.setEditable(false);
contentPane.setBounds(new java.awt.Rectangle(10, 90, 370, 150));
}returncontentPane;
}privateJButton getBtnLogin() {if (btnLogin == null) {
btnLogin= new JButton("登录");
btnLogin.setBounds(new java.awt.Rectangle(150, 45, 100, 22));
btnLogin.addActionListener(this); //注册监听事件
}returnbtnLogin;
}public voidactionPerformed(ActionEvent e) {//在这里添加按下按钮后的触发事件
}
}