终于明白为什么教科书上都喜欢用构造方法构造窗体。而不是直接写在main里

来源:互联网 发布:什么软件 看翡翠台 编辑:程序博客网 时间:2024/05/02 02:58
package com.study;


import java.awt.*;
import javax.swing.*;
import java.awt.event.*;
//Cannot make a static reference to the non-static field txtUser
//不能对非静态字段 txtUser 进行静态引用

public class QQLogin2 extends JFrame implements ActionListener {
/**
* 属性serialVersionUID
*/
private static final long serialVersionUID = 1L;
JTextField txtUser = new JTextField();
JPasswordField txtPass = new JPasswordField();


//构造方法-终于明白为什么教科书上都喜欢用构造方法构造窗体。而不是直接写在main里。

//(因为main是静态的方法,里面不能直接使用-非静态的成员。liuhailun20150317)

public QQLogin2() {
this.setSize(250, 125);


// new组件
JLabel labUser = new JLabel("用户名");
JLabel labPass = new JLabel("密码");


JButton btnLogin = new JButton("登陆");
JButton btnReg = new JButton("注册");
JButton btnCancel = new JButton("取消");


// 注册事件监听
btnLogin.addActionListener(this);
btnReg.addActionListener(this);
btnCancel.addActionListener(this);


// 布置输入面板
JPanel panInput = new JPanel();
panInput.setLayout(new GridLayout(2, 2));


panInput.add(labUser);
panInput.add(txtUser);


panInput.add(labPass);
panInput.add(txtPass);


// 布置按钮面板
JPanel panButton = new JPanel();
panButton.setLayout(new FlowLayout());


panButton.add(btnLogin);
panButton.add(btnReg);
panButton.add(btnCancel);


// 布置窗体
this.setLayout(new BorderLayout());


this.add(panInput, BorderLayout.CENTER);
this.add(panButton, BorderLayout.SOUTH);


}


public static void main(String args[]) {
QQLogin2 w = new QQLogin2();
w.setVisible(true);
}


@Override
public void actionPerformed(ActionEvent arg0) {
if (arg0.getActionCommand().equals("登陆")) {
String u = txtUser.getText();
String p = txtPass.getPassword().toString();
}
if (arg0.getActionCommand().equals("注册")) {
System.out.println("用户点了注册");
}
if (arg0.getActionCommand().equals("取消")) {
System.out.println("用户点了取消");
}
}
}
0 0