import java.awt.*;
import java.awt.event.*;
class MouseAndKey
{
private Frame frame;
private Button but;
private TextField tf;
MouseAndKey(){
init();
}
public void init(){//初始化對象
frame=new Frame("javatest.exe");
frame.setBounds(400,400,500,400);
frame.setLayout(new FlowLayout());
but=new Button("測試按鈕");
tf=new TextField(10);
frame.add(but);
frame.add(tf);
frame.setVisible(true);
myEvent();
}
public void myEvent(){
tf.addKeyListener(new KeyAdapter(){//給文本框加入鍵盤監視器
public void KeyPressed(KeyEvent e){
int code=e.getKeyCode();
if(!(code>=KeyEvent.VK_0 && code<=KeyEvent.VK_9)){
System.out.println(KeyEvent.getKeyText(code)+":非法字符");
e.consume();
}
}
});
frame.addWindowListener(new WindowAdapter(){//給窗體加入窗體適配器
public void windowClosing(WindowEvent e){
System.out.println("窗體動作,關閉窗體");
System.exit(0);
}
});
but.addActionListener(new ActionListener(){//給按鈕加入活動監視器
public void actionPerformed(ActionEvent e){
System.out.println("按鈕動作!");
}
});
but.addMouseListener(new MouseAdapter(){//給按鈕加入鼠標適配器
public void mouseClicked(MouseEvent me){
if(me.getClickCount()==2){
System.out.println("雙標事件,雙擊兩次退出窗口");
System.exit(0);
}
System.out.println("鼠標事件,單擊了一次");
}
public void mouseEntered(MouseEvent me){
System.out.println("鼠標事件,鼠標進入");
}
});
but.addKeyListener(new KeyAdapter(){//給按鈕加入鍵盤適配器
public void keyPressed(KeyEvent e){
System.out.println("鍵盤動作,鍵盤按下");
}
});
}
public static void main(String[] args)
{
new MouseAndKey();
System.out.println("Hello World!");
}
}
//賬號文本框監聽鍵盤事件
zhangHao.addKeyListener(new KeyAdapter(){
public void keyPressed(KeyEvent e){
if(e.getKeyChar()==KeyEvent.VK_ENTER){
dL.doClick();
}
}
});
//密碼文本框監聽鍵盤事件
pass.addKeyListener(new KeyAdapter(){
public void keyPressed(KeyEvent e){
if(e.getKeyChar()==KeyEvent.VK_ENTER){
dL.doClick();
}
}
});