这个例子插入了文本框,进入按钮,单件按钮,双击按钮等操作事件!
package com.xywei.awt;
import java.awt.Button;
import java.awt.FlowLayout;
import java.awt.Frame;
import java.awt.TextArea;
import java.awt.TextField;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.KeyAdapter;
import java.awt.event.KeyEvent;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;
public class MyFrame_2 {
Frame fr = new Frame();
Button bt = new Button();
TextField txf = new TextField(70);
TextArea txa = new TextArea();
public void MouseAndKeyEvent() {
fr.setBounds(400, 100, 600, 400);
fr.setLayout(new FlowLayout());
fr.setTitle("该示例是显示键盘和鼠标的示例");
bt.setLabel("按钮");
fr.add(txf);
txf.setSize(300, 300);
fr.add(bt);
// bt.setSize(200, 100);
fr.setVisible(true);
myEvent();
}
public void myEvent() {
fr.addWindowListener(new WindowAdapter() {
public void windowClosing(WindowEvent e) {
System.out.println("准备关闭窗口……");
System.out.println("已经关闭");
System.exit(0);
}
});
txf.addKeyListener(new KeyAdapter() {
/**
* @parame keyPressed 设置键盘监听事件,设置只能输入0到9数字
* 可以使用删除键删除数字
*/
public void keyPressed(KeyEvent e) {
// 设置获得的按键号,ASCII存放的
int keycode = e.getKeyCode();
if (!(keycode >= KeyEvent.VK_0 && keycode <= KeyEvent.VK_9)) {
if (keycode != KeyEvent.VK_BACK_SPACE) {
System.out.println(keycode + "===按键非法!!!!!!===");
e.consume();
}
}
}
});
bt.addActionListener(new ActionListener() {
int countClick=0;
/**
* 点击鼠标事件
* @Override
*/
public void actionPerformed(ActionEvent e) {
// TODO Auto-generated method stub
System.out.println((++countClick)+"===点击鼠标===");
}
});
bt.addMouseListener(new MouseAdapter() {
int count=1;
/**
* @param mouseEntered 只要鼠标活动进入了按钮
* 就显示出来!
*/
public void mouseEntered(MouseEvent e) {
System.out.println((count++ )+"===鼠标进入了按钮===");
}
/**
* mouseClicked 双击鼠标事件
*/
public void mouseClicked(MouseEvent e) {
int doubleClick=1;
if(e.getClickCount()==2){
System.out.println("==="+ (++doubleClick)+"===您双击了鼠标===");
}
}
});
}
/**
* 监听键盘输入的数字是否是0-9
*
* @param args
*/
public static void main(String[] args) {
// TODO Auto-generated method stub
new MyFrame_2().MouseAndKeyEvent();
}
}