import javax.swing.*;
import java.awt.*;
import java.awt.event.*; //導入事件包中的所有類
public class TextApp extends JFrame implements ActionListener{
private JLabel label1,label2,label3;
private JTextField inputText;
private JPasswordField inputPwd;
public TextApp(){
super("單行文本框的應用");
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
label1=new JLabel("用戶名稱:");
label2=new JLabel("登陸密碼:");
inputText = new JTextField(" ",27);
inputPwd = new JPasswordField(27);
label3= new JLabel();
inputText.addActionListener(this);//添加監聽器
inputPwd.addActionListener(this);
Container cp= getContentPane();
cp.setLayout(new FlowLayout());
cp.add(label1);
cp.add(inputText);
cp.add(label2);
cp.add(inputPwd);
cp.add(label3);
setSize(400,200);
}
public void actionPerformed(ActionEvent e){ //對回車事件的處理
if(e.getSource()==inputText)
{if (inputText.getText().indexOf('@') != -1) label3.setText("含有非法字符");}
else if(e.getSource()==inputPwd){
if (inputPwd.getPassword().length > 10 ) label3.setText("密碼太長,請重新輸入");
else if(inputPwd.getPassword().length < 6)
label3.setText("密碼太短,請重新輸入");
else
label3.setText("成功");}
}
public static void main(String args[]){
TextApp frame=new TextApp();
frame.setVisible(true);
}
}