1. public static void main(String[] args) {
    2. Frame f = new Frame("MouseListener");
    3. f.setSize(400, 600);
    4. f.setLocation(500, 50);
    5. f.setVisible(true);
    6. f.setLayout(new FlowLayout());
    7. f.addWindowListener(new WindowAdapter(){
    8. @Override
    9. public void windowClosing(WindowEvent e) {
    10. System.out.println("windowClosing()");
    11. System.exit(0);
    12. }
    13. });
    14. Button b1 = new Button("button1");
    15. Button b2 = new Button("button2");
    16. f.add(b1);
    17. f.add(b2);
    18. /**
    19. * 使用动作监听器监听鼠标单击按钮事件
    20. * 创建动作监听器
    21. */
    22. ActionListener myActionListener = new ActionListener() {
    23. @Override
    24. public void actionPerformed(ActionEvent e) {
    25. System.out.println("actionPerformed:" + e.getActionCommand());
    26. }
    27. };
    28. /**
    29. * 向按钮添加动作监听器
    30. */
    31. b1.addActionListener(myActionListener);
    32. b2.addActionListener(myActionListener);
    33. }