所有的组件都有鼠标和键盘监听器
import java.awt.Button; import java.awt.FlowLayout; import java.awt.Frame; import java.awt.TextField; import java.awt.event.MouseAdapter; import java.awt.event.MouseEvent; import java.awt.event.WindowAdapter; import java.awt.event.WindowEvent; class MouseDemo { private Frame f; private TextField tf; private Button bun; public MouseDemo() { init(); } public void init() { f = new Frame("演示鼠标监听"); f.setSize(600,500);//设置窗体大小,横坐标,从坐标 f.setLocation(300,200);//设置窗体显示的位置 f.setLayout(new FlowLayout()); tf = new TextField(15); bun = new Button("Yes"); f.add(tf); f.add(bun); MyEvent(); f.setVisible(true); } private void MyEvent() { f.addWindowListener(new WindowAdapter() { @Override public void windowClosing(WindowEvent e) { System.exit(0); super.windowClosing(e); } }); //在按钮上添加鼠标监听 bun.addMouseListener(new MouseAdapter() { private int count = 0; @Override public void mouseEntered(MouseEvent e) { System.out.println("mouse enter"+count++); tf.setText(count+""); super.mouseEntered(e); } @Override public void mouseClicked(MouseEvent e) { if(e.getClickCount()==2){ //实现双击 System.out.println("mouse click"+count++); } //System.out.println("mouse click"+count++); super.mouseClicked(e); } }); } public static void main(String[] args){ new MouseDemo(); } }
当一个按钮(组件)中绑定了两个监听器,一个是鼠标监听,一个是活动监听,那么鼠标监听先执行