java键盘监听keyadapter_java鼠标与键盘事件监听

packagecn.stat.p3.windowdemo;importjava.awt.Button;importjava.awt.FlowLayout;importjava.awt.Frame;importjava.awt.TextField;importjava.awt.event.KeyAdapter;importjava.awt.event.KeyEvent;importjava.awt.event.MouseAdapter;importjava.awt.event.MouseEvent;importjava.awt.event.WindowAdapter;importjava.awt.event.WindowEvent;public classshijiandemo {privateFrame f;privateTextField tf;privateButton but;/***@paramargs*/

public static voidmain(String[] args) {//TODO Auto-generated method stub

newshijiandemo() ;

}publicshijiandemo() {super();

init();

}private voidinit() {

f=new Frame("鼠标与键盘事件监听");

f.setBounds(200,200,400,400);

f.setLayout(newFlowLayout());

tf=new TextField(15);

but=new Button("这是一个按钮");

f.add(tf);

f.add(but);

f.setVisible(true);

myevent();

}private voidmyevent() {//添加键盘事件

tf.addKeyListener(newKeyAdapter() {

@Overridepublic voidkeyPressed(KeyEvent e) {//设定只能输入数字

int code=e.getKeyCode();if(!(code>=KeyEvent.VK_0 && code<=KeyEvent.VK_9))

{

System.out.println("必须是数字");

e.consume();

}

}

});//添加窗体事件

f.addWindowListener(newWindowAdapter() {

@Overridepublic voidwindowClosing(WindowEvent e) {//TODO Auto-generated method stub

System.exit(0);

}

});//添加鼠标事件

but.addMouseListener(newMouseAdapter() {

@Overridepublic voidmouseClicked(MouseEvent e) {if(e.getClickCount()==1)

{

tf.setText("单击了");

}if(e.getClickCount()==2)

{

tf.setText("双击了");

}

}private int count=0;

@Overridepublic voidmouseEntered(MouseEvent e) {

but.setLabel("鼠标触发了"+count++);

}

});

}

}

表情包
插入表情
评论将由博主筛选后显示,对所有人可见 | 还能输入1000个字符
相关推荐
©️2020 CSDN 皮肤主题: 数字20 设计师:CSDN官方博客 返回首页