zoukankan      html  css  js  c++  java
  • 201871010133-赵永军《面向对象程序设计(java)》第十三周学习总结

    201871010133-赵永军《面向对象程序设计(java)》第十三周学习总结

    项目 内容
    这个作业属于哪个课程 https://www.cnblogs.com/nwnu-daizh/
    这个作业的要求在哪里 https://www.cnblogs.com/nwnu-daizh/p/11888568.html
    作业学习目标

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

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

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

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

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

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

     

     

     

     

     

     

     

     

     

    一:理论部分。

    1.事件处理基础。

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

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

      3)事件对象:Java将事件的相关信息封装在一个事件对象中,所有的事件对象都最终派生于java.util.EventObject类。

      4)监听器对象:是一个实现了特定监听器接口的类实例。

    2.GUI设计:GUI设计中,程序员需要对组件的某种事件进行响应和处理时,必须完成两个步骤:

      1) 定义实现某事件监听器接口的事件监听器类,并具体化接口中声明的事件处理抽象方法。

      2) 为组件注册实现了规定接口的事件监听器对象;

        注册监听器方法:eventSourceObject.addEventListener(eventListenerObject)

    3.监听器接口的实现:监听器类必须实现与事件源相对应的接口,即必须提供接口中方法的实现。

    4.适配器类:当程序用户试图关闭一个框架窗口时,Jframe对象就是WindowEvent的事件源。

      适配器类动态地满足了Java中实现监视器类的技术要求。

      通过扩展适配器类来实现窗口事件需要的动作。

    5.动作接口及其类:Swing包提供了非常实用的机制来封装命令,并将它们连接到多个事件源,这就是Action接口。

      Action是一个接口,而不是一个类,实现这个接口的类必须要实现它的7个方法。

      AbstractAction 类 实 现 了 Action 接 口 中 除actionPerformed方法之外的所有方法,这个类存储了所有名/值对,并管理着属性变更监听器。

    6.鼠标事件:MouseEvent.

      鼠标监听器接口:MouseListener,MouseMotionListener

      鼠标监听器适配器:MouseAdapter,MouseMotionAdapter

      用户点击鼠标按钮时,会调用三个监听器方法:
        a.鼠标第一次被按下时调用mousePressed方法;
        b.鼠标被释放时调用mouseReleased方法;
        c.两个动作完成之后,调用mouseClicked方法。

      鼠标在组件上移动时,会调用mouseMoved方法。

    7.鼠标事件返回值:鼠标事件的类型是MouseEvent,当发生鼠标事件时:

      MouseEvent类自动创建一个事件对象,以及事件发生位置的x和y坐标,作为事件返回值。

      监听鼠标点击事件,实现MouseListener接口.

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

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

    二:实验部分。

    1、实验目的与要求

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

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

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

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

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

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

    2、实验内容和步骤

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

    测试程序1:

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

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

    ※用lambda表达式简化程序;

    ※掌握JButton组件的基本API;

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

    实验程序如下:

     1 import java.awt.*;
     2 import java.awt.event.*;
     3 import javax.swing.*;
     4 
     5 /**
     6  * 带有按钮的面板框架
     7  */
     8 public class ButtonFrame extends JFrame//继承
     9 {
    10    private JPanel buttonPanel;
    11    private static final int DEFAULT_WIDTH = 300;
    12    private static final int DEFAULT_HEIGHT = 200;
    13 
    14    public ButtonFrame()//构造器
    15    {      
    16       setSize(DEFAULT_WIDTH, DEFAULT_HEIGHT);
    17       
    18      
    19       buttonPanel = new JPanel();
    20 
    21       makeButton("yellow",Color.YELLOW);
    22       makeButton("yellow",Color.BLUE);
    23       makeButton("yellow",Color.RED);
    24       makeButton("yellow",Color.GREEN);
    25     add(buttonPanel);
    26 }
    27    public void makeButton(String name,Color backgroundColor)
    28    {
    29        JButton button =new JButton(name);
    30        buttonPanel.add(button);
    31        button.addActionListener(event ->
    32                buttonPanel.setBackground(backgroundColor));
    33    }
    34 }
     1 import java.awt.*;
     2 import javax.swing.*;
     3 
     4 
     5 /**
     6  * @version 1.34 2015-06-12
     7  * @author Cay Horstmann
     8  */
     9 public class ButtonTest
    10 {
    11    public static void main(String[] args)
    12    {
    13       EventQueue.invokeLater(() ->//lambda表达式
    14       {
    15          JFrame frame = new ButtonFrame();
    16          frame.setTitle("ButtonTest");//标题
    17          frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    18          frame.setVisible(true);//可见
    19       });
    20    }
    21 }

    实验结果如下:

    测试程序2:

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

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

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

    实验程序如下:

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

    实验结果如下:

     

     

     

     

     

     

    测试程序3:

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

    ※掌握AbstractAction类及其动作对象;

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

    实验程序如下:

     1 import java.awt.*;
     2 import javax.swing.*;
     3 
     4 /**
     5  * @version 1.34 2015-06-12
     6  * @author Cay Horstmann
     7  */
     8 public class ActionTest
     9 {
    10    public static void main(String[] args)
    11    {
    12       EventQueue.invokeLater(() -> //lambda表达式
    13       {
    14          JFrame frame = new ActionFrame();
    15          frame.setTitle("ActionTest");//标题
    16          frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    17          frame.setVisible(true);//可见
    18       });
    19    }
    20 }
     1 import java.awt.*;
     2 import java.awt.event.*;
     3 import javax.swing.*;
     4 
     5 /**
     6  * A frame with a panel that demonstrates color change actions.
     7  */
     8 public class ActionFrame extends JFrame//继承
     9 {
    10    private JPanel buttonPanel;
    11    private static final int DEFAULT_WIDTH = 300;
    12    private static final int DEFAULT_HEIGHT = 200;
    13 
    14    public ActionFrame()//构造器
    15    {
    16       setSize(DEFAULT_WIDTH, DEFAULT_HEIGHT);
    17 
    18       buttonPanel = new JPanel();
    19 
    20       //定义按钮行为
    21       Action yellowAction = new ColorAction("Yellow", new ImageIcon("yellow-ball.gif"),
    22             Color.YELLOW);
    23       Action blueAction = new ColorAction("Blue", new ImageIcon("blue-ball.gif"), Color.BLUE);
    24       Action redAction = new ColorAction("Red", new ImageIcon("red-ball.gif"), Color.RED);
    25 
    26       // add buttons for these actions
    27       buttonPanel.add(new JButton(yellowAction));
    28       buttonPanel.add(new JButton(blueAction));
    29       buttonPanel.add(new JButton(redAction));
    30 
    31       // add panel to frame
    32       add(buttonPanel);
    33 
    34       // 将Y、B和R键与名称关联起来
    35       InputMap imap = buttonPanel.getInputMap(JComponent.WHEN_ANCESTOR_OF_FOCUSED_COMPONENT);
    36       imap.put(KeyStroke.getKeyStroke("ctrl Y"), "panel.yellow");
    37       imap.put(KeyStroke.getKeyStroke("ctrl B"), "panel.blue");
    38       imap.put(KeyStroke.getKeyStroke("ctrl R"), "panel.red");
    39 
    40       // associate the names with actions
    41       ActionMap amap = buttonPanel.getActionMap();
    42       amap.put("panel.yellow", yellowAction);
    43       amap.put("panel.blue", blueAction);
    44       amap.put("panel.red", redAction);
    45    }
    46    
    47    public class ColorAction extends AbstractAction
    48    {
    49       /**
    50        * Constructs a color action.
    51        * @param name the name to show on the button
    52        * @param icon the icon to display on the button
    53        * @param c the background color
    54        */
    55       public ColorAction(String name, Icon icon, Color c)//构造器
    56       {
    57          putValue(Action.NAME, name);
    58          putValue(Action.SMALL_ICON, icon);
    59          putValue(Action.SHORT_DESCRIPTION, "Set panel color to " + name.toLowerCase());
    60          putValue("color", c);
    61       }
    62 
    63       public void actionPerformed(ActionEvent event)//按钮单击方法
    64       {
    65          Color c = (Color) getValue("color");
    66          buttonPanel.setBackground(c);
    67       }
    68    }
    69 }

    程序运行时只需同时按Ctrl+Y或R或B键,窗口就会自动显示某种颜色,如下:

    测试程序4:

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

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

    实验程序如下:

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

    实验结果如下:

    实验2:结对编程练习

    利用班级名单文件、文本框和按钮组件,设计一个有如下界面(图1)的点名器,要求用户点击开始按钮后在文本输入框随机显示2018级计算机科学与技术(1)班同学姓名,如图2所示,点击停止按钮后,文本输入框不再变换同学姓名,此同学则是被点到的同学姓名,如图3所示。

    结对编程思路:

      我们先设计了一个GUI图形界面,然后将学生信息读取后存储带一个数组当中,在实现监听器类actionPerformed方法时,采用随机数下标获取学生信息数组中的值,再重写timer类的schedule类中的run方法实现定时器功能。当button中的内容为“开始”时,启动定时器,当button中的内容为“停止”时,则调用timer类对象的cancel方法停用定时器,这样就完成了对点名器的代码编程。

    实验程序如下:

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

    实验结果如下:

     

    结对编程照片:

    三、实验总结

      这周学习了如何对事件进行处理,比如通过点击按钮或者鼠标对界面进行操控,对于图形用户界面的程序来说,事件处理显得十分重要。通过实验课上学长演示实验,再用lambda表达式以及匿名类等简化程序,使得自己对实验有了更多的了解。通过和合作伙伴结对编程,合作完成点名器的实验,对事件处理机制有了更深的体会。但是这个实验还是借助了外力才得以完成,有一些地方还是不懂,经过看书和同学的讲解,才得以理解。

  • 相关阅读:
    Socket网络通信之数据传递
    多线程中join()的用法
    JAVA多线程实现的三种方式
    通过读取配置文件,启动mongodb
    利用ajax获取网页表单数据,并存储到数据库之二(使用SSH)
    利用ajax获取网页表单数据,并存储到数据库之一(使用JDBC)
    Null reference pointer was passed to the stub when not debugging with IE
    代码生成了解
    Linq to sql 入门
    SharePoint 2013 入门
  • 原文地址:https://www.cnblogs.com/zhaoyongjun0911/p/11922433.html
Copyright © 2011-2022 走看看