下面使用Java的TextField组件来实现登录页面。
TextField 对象是允许编辑单行文本的文本组件。每次用户在文本字段中键入一个键,就有一个或更多键事件被发送到该文本字段。KeyEvent可以是以下三种类型之一:keyPressed、keyReleased 或
keyTyped。键事件的属性指示事件是这些类型中的哪一种,以及关于事件的其他信息,比如将哪种修改器应用于键事件和发生事件的时间。
键事件被传递给每一个 KeyListener 或 KeyAdapter 对象,这些对象使用组件的
addKeyListener 方法注册,以接收这类事件。(KeyAdapter 对象实现
KeyListener 接口。)
TextField 还可能触发 ActionEvent。如果为文本字段启用操作事件,则可以通过按下
Return 键触发它们。
TextField 类的 processEvent 方法检查操作事件,并将它们传递给
processActionEvent。后一种方法将该事件重定向到为接收此文本字段生成的操作事件而注册的所有
ActionListener 对象。
实例(登录页面):
import java.awt.*;
import java.awt.event.*;
public class TestTextField implements ActionListener{
TextField name;
TextField password;
public static void main( String args[]) {
TestTextField ttf = new TestTextField();
ttf.createUI();
}
public void createUI(){
Frame f = new Frame("登录界面");
f.add(new Label("请输入您的用户信息:"),"North");
Panel p1 = new Panel();
p1.setLayout(new BorderLayout());
Panel p11 = new Panel();
p11.setLayout(new GridLayout(2,1));
p11.add(new Label("用户名:"));
p11.add(new Label("密 码:"));
Panel p12 = new Panel();
p12.setLayout(new GridLayout(2,1));
name = new TextField(10);
name.addActionListener(this);
password = new TextField(10);
password.setEchoChar('*');
password.addActionListener(this);
p12.add(name);
p12.add(password);
p1.add(p11,"West");
p1.add(p12,"Center");
Panel p2 = new Panel();
Button submit = new Button("提交");
Button reset = new Button("重置");
submit.addActionListener(this);
reset.addActionListener(this);
p2.add(submit);
p2.add(reset);
f.add(p1,"Center");
f.add(p2,"South");
f.addWindowListener(new WindowAdapter(){
public void windowClosing(WindowEvent e){
System.exit(0);
}
});
f.setSize(200,130);
f.setLocation(300,200);
f.setVisible( true);
}
public void actionPerformed(ActionEvent e){
String s = e.getActionCommand();
if(s.equals("重置")){
this.clear();
}else if(s.equals("提交") || (e.getSource()==name) || (e.getSource()==password)){
this.submit();
}
}
public void clear(){
name.setText("");
password.setText("");
}
public void submit(){
String n = name.getText();
String psw = password.getText();
System.out.println("用户名:" + n + " 密码:" + psw);
}
}效果图(点击提交将会把用户名和密码输出到终端):
