王之泰201771010131《面向对象程序设计(java)》第十三周学习总结

第一部分:理论知识学习部分

 第11章 事件处理

 11.1 事件处理基础

a)事件源(event source):能够产生事件的对象都可 以成为事件源,如文本框、按钮等。一个事件源是一个 能够注册监听器并向监听器发送事件对象的对象。

b) 事件监听器(event listener):事件监听器对象接 收事件源发送的通告(事件对象),并对发生的事件作 出响应。一个监听器对象就是一个实现了专门监听器接 口的类实例,该类必须实现接口中的方法,这些方法当 事件发生时,被自动执行。

c) 事件对象(event object):Java将事件的相关信息 封装在一个事件对象中,所有的事件对象都最终派生于 java.util.EventObject类。不同的事件源可以产生不 同类别的事件。

11.2 动作

a) 激活一个命令可以有多种方式,如用户可以通过 菜单、击键或工具栏上的按钮选择特定的功能。 

b) 在AWT事件模型中,无论是通过哪种方式下达命 令(如:点击按钮、菜单选项、按下键盘),其 操作动作都是一样的。

11.3 鼠标事件

a)鼠标事件 – MouseEvent 

b)鼠标监听器接口 – MouseListener – MouseMotionListener 

c) 鼠标监听器适配器 – MouseAdapter – MouseMotionAdapter

11.4 AWT事件继承层次

a) 所有的事件都是由java.util包中的EventObject 类扩展而来。 

b) AWTEevent 是所有AWT 事件类的父类, 也是 EventObject的直接子类。 

c) 有些Swing组件生成其他类型的事件对象,一般直 接 扩 展 于 EventObject, 而不是AWTEvent,位于 javax.swing.event.*。

d) 事件对象封装了事件源与监听器彼此通信的事件 信息。在必要的时候,可以对传递给监听器对象的 事件对象进行分析。

第二部分:实验部分——图形界面事件处理技术

实验时间 2018-11-22

1、实验目的与要求

(1) 掌握事件处理的基本原理,理解其用途;

(2) 掌握AWT事件模型的工作机制;

(3) 掌握事件处理的基本编程模型;

(4) 了解GUI界面组件观感设置方法;

(5) 掌握WindowAdapter类、AbstractAction类的用法;

(6) 掌握GUI程序中鼠标事件处理技术。

2、实验内容和步骤

实验1: 导入第11章示例程序,测试程序并进行代码注释。

测试程序1:

1.在elipse IDE中调试运行教材443页-444页程序11-1,结合程序运行结果理解程序;

2.在事件处理相关代码处添加注释;

3.用lambda表达式简化程序;

4.掌握JButton组件的基本API;

5.掌握Java中事件处理的基本编程模型。

 1 package test;
 2 
 3 import java.awt.*;
 4 import java.awt.event.*;
 5 import javax.swing.*;
 6 
 7 /**
 8  * 带按钮面板的框架
 9  */
10 
11  
12 public class ButtonFrame extends JFrame
13 {
14    private JPanel buttonPanel;
15    private static final int DEFAULT_WIDTH = 500;
16    private static final int DEFAULT_HEIGHT = 600;
17 
18    public ButtonFrame()
19    {      
20       setSize(DEFAULT_WIDTH, DEFAULT_HEIGHT);
21 
22       // 创建三个按钮 
23 //      JButton yellowButton = new JButton("Yellow");
24 //      JButton blueButton = new JButton("Blue");
25 //      JButton redButton = new JButton("Red");
26 
27       buttonPanel = new JPanel();
28 
29        // 向面板添加按钮
30 //      buttonPanel.add(yellowButton);
31 //      buttonPanel.add(blueButton);
32 //      buttonPanel.add(redButton);
33 
34       // 将面板添加到帧
35       add(buttonPanel);
36 
37 //       创建按钮动作
38 //      ColorAction yellowAction = new ColorAction(Color.YELLOW);
39 //      ColorAction blueAction = new ColorAction(Color.BLUE);
40 //      ColorAction redAction = new ColorAction(Color.RED);
41 //
42 //       用按钮关联动作
43 //      yellowButton.addActionListener(yellowAction); 
44 //      blueButton.addActionListener(blueAction);
45 //      redButton.addActionListener(redAction);
46    
47    MakeButton("黄色",Color.yellow); 
48    MakeButton("蓝色",Color.blue); 
49    MakeButton("红色",Color.red);
50    }
51    public void MakeButton(String name , Color backgroundColor) 
52    { 
53        JButton button=new JButton(name); 
54        buttonPanel.add(button); 
55 //       ColorAction action=new ColorAction(backgroundColor); 
56 //       button.addActionListener(action); 
57        button.addActionListener(new ActionListener() 
58        { 
59            public void actionPerformed(ActionEvent event) 
60            {           
61                buttonPanel.setBackground(backgroundColor); 
62                } 
63            });
64 
65    } 
66    
67 
68    /**
69     * 设置面板背景颜色的动作侦听器
70     */
71    private class ColorAction implements ActionListener
72    {
73       private Color backgroundColor;
74 
75       public ColorAction(Color c)
76       {
77          backgroundColor = c;
78       }
79 
80       public void actionPerformed(ActionEvent event)
81       {
82          buttonPanel.setBackground(backgroundColor);
83       }
84    }
85 }
 1 package button;
 2 
 3 import java.awt.*;
 4 import javax.swing.*;
 5 
 6 /**
 7  * @version 1.34 2015-06-12
 8  * @author Cay Horstmann
 9  */
10 public class ButtonTest
11 {
12    public static void main(String[] args)
13    {
14       EventQueue.invokeLater(() -> {
15          JFrame frame = new ButtonFrame();
16          frame.setTitle("ButtonTest");
17          frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
18          frame.setVisible(true);
19       });
20    }
21 }

测试程序2:

1.在elipse IDE中调试运行教材449页程序11-2,结合程序运行结果理解程序;

2.在组件观感设置代码处添加注释;

3.了解GUI程序中观感的设置方法。

 1 package plaf;
 2 
 3 import javax.swing.JButton;
 4 import javax.swing.JFrame;
 5 import javax.swing.JPanel;
 6 import javax.swing.SwingUtilities;
 7 import javax.swing.UIManager;
 8 
 9 /**
10  * 带有按钮面板的框架,用于改变外观和感觉
11  */
12 public class PlafFrame extends JFrame
13 {
14    private JPanel buttonPanel;
15 
16    public PlafFrame()
17    {
18       buttonPanel = new JPanel();
19 
20       UIManager.LookAndFeelInfo[] infos = UIManager.getInstalledLookAndFeels();
21       for (UIManager.LookAndFeelInfo info : infos)
22          makeButton(info.getName(), info.getClassName());
23 
24       add(buttonPanel);
25       pack();
26    }
27 
28    /**
29     * 制作一个按钮来改变可插拔的外观和感觉.
30     * @param 命名按钮名称
31     * @param 类名:外观类的名称
32     */
33    private void makeButton(String name, String className)
34    {
35       // 向面板添加按钮
36 
37       JButton button = new JButton(name);
38       buttonPanel.add(button);
39 
40       // 设置按钮动作
41 
42       button.addActionListener(event -> {
43          //按钮动作:切换到新的外观和感觉
44          try
45          {
46             UIManager.setLookAndFeel(className);
47             SwingUtilities.updateComponentTreeUI(this);
48             pack();
49          }
50          catch (Exception e)
51          {
52             e.printStackTrace();
53          }
54       });
55    }
56 }
 1 package plaf;
 2 
 3 import java.awt.*;
 4 import javax.swing.*;
 5 
 6 /**
 7  * @version 1.32 2015-06-1222222222222222222222222222
 8  * @author Cay Horstmann
 9  */
10 public class PlafTest
11 {
12    public static void main(String[] args)
13    {
14       EventQueue.invokeLater(() -> {
15          JFrame frame = new PlafFrame();
16          frame.setTitle("PlafTest");
17          frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
18          frame.setVisible(true);
19       });
20    }
21 }

测试程序3:

1.在elipse IDE中调试运行教材457页-458页程序11-3,结合程序运行结果理解程序;

2.掌握AbstractAction类及其动作对象;

3.掌握GUI程序中按钮、键盘动作映射到动作对象的方法。

 1 package action;
 2 
 3 import java.awt.*;
 4 import javax.swing.*;
 5 
 6 /**
 7  * @version 1.34 2015-06-1233333333333333333333333333
 8  * @author Cay Horstmann
 9  */
10 public class ActionTest
11 {
12    public static void main(String[] args)
13    {
14       EventQueue.invokeLater(() -> {
15          JFrame frame = new ActionFrame();
16          frame.setTitle("ActionTest");
17          frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
18          frame.setVisible(true);
19       });
20    }
21 }
 1 package action;
 2 
 3 import java.awt.*;
 4 import java.awt.event.*;
 5 import javax.swing.*;
 6 
 7 /**
 8  * 具有显示颜色变化动作的面板的框架
 9  */
10 public class ActionFrame extends JFrame
11 {
12    private JPanel buttonPanel;
13    private static final int DEFAULT_WIDTH = 300;
14    private static final int DEFAULT_HEIGHT = 200;
15 
16    public ActionFrame()
17    {
18       setSize(DEFAULT_WIDTH, DEFAULT_HEIGHT);
19 
20       buttonPanel = new JPanel();
21 
22       // 定义动作
23       Action yellowAction = new ColorAction("Yellow", new ImageIcon("yellow-ball.gif"),
24             Color.YELLOW);
25       Action blueAction = new ColorAction("Blue", new ImageIcon("blue-ball.gif"), Color.BLUE);
26       Action redAction = new ColorAction("Red", new ImageIcon("red-ball.gif"), Color.RED);
27 
28       // 为这些操作添加按钮
29       buttonPanel.add(new JButton(yellowAction));
30       buttonPanel.add(new JButton(blueAction));
31       buttonPanel.add(new JButton(redAction));
32 
33       // 将面板添加到帧
34       add(buttonPanel);
35 
36       // 将Y、B和R键与名称关联
37       InputMap imap = buttonPanel.getInputMap(JComponent.WHEN_ANCESTOR_OF_FOCUSED_COMPONENT);
38       imap.put(KeyStroke.getKeyStroke("ctrl Y"), "panel.yellow");
39       imap.put(KeyStroke.getKeyStroke("ctrl B"), "panel.blue");
40       imap.put(KeyStroke.getKeyStroke("ctrl R"), "panel.red");
41 
42       // 把名字和动作联系起来
43       ActionMap amap = buttonPanel.getActionMap();
44       amap.put("panel.yellow", yellowAction);
45       amap.put("panel.blue", blueAction);
46       amap.put("panel.red", redAction);
47    }
48    
49    public class ColorAction extends AbstractAction
50    {
51       /**
52        * 构造颜色动作。
53        * @param 在按钮上显示要显示的名称
54        * @param 图标按钮上显示的图标
55        * @param 背景颜色
56        */
57       public ColorAction(String name, Icon icon, Color c)
58       {
59          putValue(Action.NAME, name);
60          putValue(Action.SMALL_ICON, icon);
61          putValue(Action.SHORT_DESCRIPTION, "Set panel color to " + name.toLowerCase());
62          putValue("color", c);
63       }
64 
65       public void actionPerformed(ActionEvent event)
66       {
67          Color c = (Color) getValue("color");
68          buttonPanel.setBackground(c);
69       }
70    }
71 }

测试程序4:

1.在elipse IDE中调试运行教材462页程序11-4、11-5,结合程序运行结果理解程序;

2.掌握GUI程序中鼠标事件处理技术。

 1 package mouse;
 2 
 3 import java.awt.*;
 4 import javax.swing.*;
 5 
 6 /**
 7  * @version 1.34 2015-06-12
 8  * @author Cay Horstmann
 9  */
10 public class MouseTest
11 {
12    public static void main(String[] args)
13    {
14       EventQueue.invokeLater(() -> {
15          JFrame frame = new MouseFrame();
16          frame.setTitle("MouseTest");
17          frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
18          frame.setVisible(true);
19       });
20    }
21 }
 1 package mouse;
 2 
 3 import javax.swing.*;
 4 
 5 /**
 6  * 包含用于测试鼠标操作的面板的框架
 7  */
 8 public class MouseFrame extends JFrame
 9 {
10    public MouseFrame()
11    {
12       add(new MouseComponent());
13       pack();
14    }
15 }
  1 package mouse;
  2 
  3 import java.awt.*;
  4 import java.awt.event.*;
  5 import java.awt.geom.*;
  6 import java.util.*;
  7 import javax.swing.*;
  8 
  9 /**
 10  *一个带有鼠标操作的用于添加和删除正方形的组件。
 11  */
 12 public class MouseComponent extends JComponent
 13 {
 14    private static final int DEFAULT_WIDTH = 300;
 15    private static final int DEFAULT_HEIGHT = 200;
 16 
 17    private static final int SIDELENGTH = 10;
 18    private ArrayList<Rectangle2D> squares;
 19    private Rectangle2D current; // 包含鼠标光标的正方形
 20 
 21    public MouseComponent()
 22    {
 23       squares = new ArrayList<>();
 24       current = null;
 25 
 26       addMouseListener(new MouseHandler());
 27       addMouseMotionListener(new MouseMotionHandler());
 28    }
 29 
 30    public Dimension getPreferredSize() { return new Dimension(DEFAULT_WIDTH, DEFAULT_HEIGHT); }   
 31    
 32    public void paintComponent(Graphics g)
 33    {
 34       Graphics2D g2 = (Graphics2D) g;
 35 
 36       // 绘制所有正方形
 37       for (Rectangle2D r : squares)
 38          g2.draw(r);
 39    }
 40 
 41    /**
 42     * 找到包含一个点的第一个方块。
 43     * @param P—A点
 44     * @return 包含P的第一个正方形
 45     */
 46    public Rectangle2D find(Point2D p)
 47    {
 48       for (Rectangle2D r : squares)
 49       {
 50          if (r.contains(p)) return r;
 51       }
 52       return null;
 53    }
 54 
 55    /**
 56     * 向集合中添加正方形。
 57     * @param 新闻中心
 58     */
 59    public void add(Point2D p)
 60    {
 61       double x = p.getX();
 62       double y = p.getY();
 63 
 64       current = new Rectangle2D.Double(x - SIDELENGTH / 2, y - SIDELENGTH / 2, SIDELENGTH,
 65             SIDELENGTH);
 66       squares.add(current);
 67       repaint();
 68    }
 69 
 70    /**
 71     * 从集合中移除正方形。
 72     * @param S方移除
 73     */
 74    public void remove(Rectangle2D s)
 75    {
 76       if (s == null) return;
 77       if (s == current) current = null;
 78       squares.remove(s);
 79       repaint();
 80    }
 81 
 82    private class MouseHandler extends MouseAdapter
 83    {
 84       public void mousePressed(MouseEvent event)
 85       {
 86          // 如果光标不在正方形中,则添加一个新的正方形
 87          current = find(event.getPoint());
 88          if (current == null) add(event.getPoint());
 89       }
 90 
 91       public void mouseClicked(MouseEvent event)
 92       {
 93          // 如果双击,则移除当前正方形
 94          current = find(event.getPoint());
 95          if (current != null && event.getClickCount() >= 2) remove(current);
 96       }
 97    }
 98 
 99    private class MouseMotionHandler implements MouseMotionListener
100    {
101       public void mouseMoved(MouseEvent event)
102       {
103          // 设置鼠标光标,如果里面是交叉头发
104          // 矩形
105 
106          if (find(event.getPoint()) == null) setCursor(Cursor.getDefaultCursor());
107          else setCursor(Cursor.getPredefinedCursor(Cursor.CROSSHAIR_CURSOR));
108       }
109 
110       public void mouseDragged(MouseEvent event)
111       {
112          if (current != null)
113          {
114             int x = event.getX();
115             int y = event.getY();
116 
117             // 拖动当前矩形将其置于(x,y)中心
118             current.setFrame(x - SIDELENGTH / 2, y - SIDELENGTH / 2, SIDELENGTH, SIDELENGTH);
119             repaint();
120          }
121       }
122    }   
123 }

实验2:结对编程练习

利用班级名单文件、文本框和按钮组件,设计一个有界面的点名器,要求用户点击开始按钮后在文本输入框随机显示2017级网络与信息安全班同学姓名,点击停止按钮后,文本输入框不再变换同学姓名,此同学则是被点到的同学姓名。

 

 1 package Roll_call_device;
 2 
 3 
 4 import java.awt.Color;
 5 import java.awt.FlowLayout;
 6 import java.awt.Label;
 7 import java.awt.event.ActionEvent;
 8 import java.awt.event.ActionListener;
 9 import java.io.BufferedReader;
10 import java.io.File;
11 import java.io.FileInputStream;
12 import java.io.IOException;
13 import java.io.InputStreamReader;
14 import java.util.ArrayList;
15 
16 import javax.swing.JButton;
17 import javax.swing.JFrame;
18 import javax.swing.Timer;
19 
20 public class Rollcall 
21 {
22     public static void main(String args[]) 
23     {
24         try {
25             Dmq dmq = new Dmq();
26             dmq.lab.setText("随机点名器");
27             dmq.setTitle("点名器");
28         } catch (IOException e) 
29         {
30             // TODO Auto-generated catch block
31             e.printStackTrace();
32         }
33     }
34 }
35 
36 class Dmq extends JFrame 
37 {
38     final Label lab = new Label();
39     ArrayList<String> namelist = new ArrayList<String>();
40 
41     public Dmq() throws IOException 
42     {
43         File file = new File("src/studentnamelist.txt");
44         FileInputStream fis = new FileInputStream(file);
45         InputStreamReader isr = new InputStreamReader(fis, "GBK");
46         BufferedReader br = new BufferedReader(isr);
47         String line = "";
48         while ((line = br.readLine()) != null) 
49         {
50             if (line.lastIndexOf("---") < 0) 
51             {
52                 namelist.add(line);
53             }
54         }
55         setBounds(550, 270, 200, 150);
56         final Timer timer = new Timer(50, new ActionListener() 
57         {
58             public void actionPerformed(ActionEvent e) 
59             {
60                 lab.setText(namelist.get((int) (Math.random() * namelist.size())));
61             }
62         });
63 
64         JButton jbutton = new JButton("开始");
65         jbutton.addActionListener(new ActionListener() 
66         {
67             public void actionPerformed(ActionEvent e) 
68             {
69                 JButton jbutton = (JButton) e.getSource();
70                 if (jbutton.getText().equals("开始")) 
71                 {
72                     jbutton.setText("停止");
73                     timer.start();
74                 } else if (jbutton.getText().equals("停止")) 
75                 {
76                     jbutton.setText("开始");
77                     timer.stop();
78                 }
79 
80             }
81         });
82         jbutton.setBounds(30, 30, 30, 30);
83         lab.setBackground(new Color(255, 255, 255));
84         this.setLayout(new FlowLayout());
85         this.add(lab);
86         this.add(jbutton);
87         this.setSize(300, 200);
88         this.setVisible(true);
89         this.setDefaultCloseOperation(EXIT_ON_CLOSE);
90         br.close();
91     }
92 
93 }

第三部分:总结

     通过本周的学习,我掌握了事件处理的基本原理,理解了用途;并了解学习了以下几点。AWT事件模型的工作机制;事件处理的基本编程模型;了解了GUI界面组件观感设置方法;WindowAdapter类、AbstractAction类的用法;GUI程序中鼠标事件处理技术。并且在看了助教学长的教学视频和同学的帮助下,学会了如何设计一个小型界面,受益颇多!

原文地址:https://www.cnblogs.com/hackerZT-7/p/10002361.html