【一】鼠标键盘事件
1.鼠标事件
鼠标进入事件组:mouseEntered(MouseEvent e)
鼠标点击事件:mouseClicked(MouseEvent e)
判断鼠标双击事件:
public void mouseClicked(MouseEvent e){
if(e.getClickCount()==2){
System.out.println("双击动作"+(clickCount++));
}
}
2.键盘事件
键盘敲击事件:keyPressed(KeyEvent e)
组合建:
but.addKeyListener(new KeyAdapter(){
public void keyPressed(KeyEvent e){
if(e.isControlDown()&&e.getKeyCode()==KeyEvent.VK_H)
System.out.println("control"+"H");
}
});
是非法字符不在文本框中出现
tf=new TextField(20);
f.add(tf);
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(code+"是非法的");
e.consume();//是非法字符不在文本框中出现
}
}
});
【二】代码示例
import java.awt.*;
import java.awt.event.*;
class Demo
{
private Frame f;
private Button but;
private TextField tf;
Demo(){
init();
}
public void init(){
f=new Frame("鼠标键盘事件");
but=new Button("确认");
tf=new TextField(11);
f.setBounds(100,200,300,250);
f.setLayout(new FlowLayout());
myEvent();
f.setVisible(true);
f.add(tf);
f.add(but);
}
public void myEvent(){
f.addWindowListener(new WindowAdapter(){
public void windowClosing(WindowEvent e){
System.out.println("关闭窗口");
System.exit(0);//___
}
});
but.addMouseListener(new MouseAdapter(){
public void mouseClicked(MouseEvent e){
if(e.getClickCount()==2)
System.out.println("双击确认按钮");
}
});
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("非法字符:"+code);
e.consume();
}
}
});
}
public static void main(String[] args)
{
new Demo();
}
}
【三】输出示例
分别点击的键盘是:1 2 3 shift s s
点击退出后: