鼠标键盘事件

【一】鼠标键盘事件

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

点击退出后:

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值