本帖最后由 杜光 于 2013-6-11 09:47 编辑
第一段鼠标监听器里覆盖了MouseListener中的抽象方法,但是第二段没有覆盖父类的方法,怎么也能执行顺利而不会报错呢??- import java.awt.*;
- import java.awt.event.*;
- class AwtDemo
- {
- public static void main(String[] args)
- {
- Frame f = new Frame("my awt");
- f.setSize(500,400);
- f.setLocation(300,200);
- f.setLayout(new FlowLayout());
- Button but = new Button("我是一个按钮");
- f.add(but);
- f.addWindowListener(new WindowAdapter()
- {
- public void windowClosing(WindowEvent e)
- {
- System.out.println("我关");
- System.exit(0);
- }
- public void windowActivated(WindowEvent e)
- {
- System.out.println("我被激活了");
- }
- public void windowOpened(WindowEvent e)
- {
- System.out.println("我被打开了,哈哈哈");
- }
- });
-
- //按键监听器
- but.addActionListener(new ActionListener ()
- {
- public void actionPerformed(ActionEvent e)
- {
- System.out.println("退出 按钮干的!");
- System.exit(0);
- }
- });
- //鼠标监听器
-
- but.addMouseListener(new MouseListener()
- {
-
- public void mouseEntered(MouseEvent e)
- {
- System.out.println("你碰到我啦!");
- }
- @Override
- public void mouseClicked(MouseEvent e)
- {
-
-
- }
- @Override
- public void mousePressed(MouseEvent e)
- {
-
-
- }
- @Override
- public void mouseReleased(MouseEvent e)
- {
-
-
- }
- @Override
- public void mouseExited(MouseEvent e)
- {
-
-
- }
- });
- f.setVisible(true);
- }
- }
复制代码 第二段代码:- import java.awt.*;
- import java.awt.event.*;
- class MouseAndKeyboard
- {
- //定义该图形中所需的组件引用
- private Frame f;
- private Button but;
- MouseAndKeyboard()
- {
- init();
- }
-
- public void init()
- {
- f = new Frame("My Frame");
- //对frame进行基本设置
- f.setBounds(300,100,500,400);
- f.setLayout(new FlowLayout());
- but = new Button("My Button");
- //将组件添加到frame中
- f.add(but);
- //加载一下窗体上事件
- myEvent();
- //现实窗体
- f.setVisible(true);
-
- }
- private void myEvent()
- {
- f.addWindowListener(new WindowAdapter()
- {
- public void windowClosing(WindowEvent e)
- {
- System.exit(0);
- }
- });
- //添加一个按钮具备退出的功能
- //按钮就是事件源,选择哪个监听器?
- //通过关闭窗体示例,知道哪个组件具备什么样的特有监听器,需要查看该组件对象的功能
- //通过查阅button的API描述,发现按钮支持一个特有监听 addActionListener.
- but.addActionListener(new ActionListener()
- {
- public void actionPerformed(ActionEvent e)
- {
- System.out.println("不和你玩了,按钮干的");
- System.exit(0);
- }
- });
- but.addMouseListener(new MouseAdapter()
- {
- private int count = 1;
- private int click = 1;
- private int click2 = 1;
- public void mouseEntered(MouseEvent e)
- {
- System.out.println("碰我"+(count++)+"次啦!!!");
- }
- public void mouseClicked(MouseEvent e)
- {
- if (e.getClickCount()==2)
- {
- System.out.println("你连点了我两下"+click2++);
- }
- System.out.println("你点到我了"+click++);
- }
- });
- }
- public static void main(String[] args)
- {
- new MouseAndKeyboard();
- }
- }
复制代码 |