zoukankan      html  css  js  c++  java
  • 201871010108-高文利《面向对象程序设计(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程序中鼠标事件处理技术。

    第一部分:总结第十一章理论知识(35分)

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

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

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

      2.AWT事件处理机制的概要;

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

      当事件发生时,事件源将事件对象自动传递给所有注册的监听器 。

      监听器对象利用事件对象中的信息决定如何对事件做出响应。

      3.事件源与监听器之间的关系:

     

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

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

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

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

     6.动作事件:当特定组件动作(点击按钮)发生时,该组件生成此动作事件。

         该事件被传递给组件注册的每一个ActionListener对象,并调用监听器对象的actionPerformed方法以接受这类事件对象。

        能够触发事件动作的动作,主要包括:

       点击按钮;双击一个列表中的选项;选择菜单项;在文本框中输入回车

    7.监听器接口的实现

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

      监听器接口的方法实现

    class MyListener implenments ActionListener

    {

        public void actionPerformed(ActionEvent event)

    {......}

    }

    8.命令按钮Jbutton主要API

    (1)创建按钮对象

    Jbutton类常用的一组构造方法;

    (1) JButton(String text):创建一个带文本的按钮。
    (2) JButton(Icon icon) :创建一个带图标的按钮。
    (3)JButton(String text, Icon icon) :创建一个带文本和图标
    的按钮

    (2)按钮对象的常用方法:

    (1) getLabel( ):返回按钮的标签字符串;

    (2) setLabel(String s):设置按钮的标签为字符串s。

    9. 用匿名类、lambda表达式简化程序

    例ButtonTest.java中,各按钮需要同样的处理:
    1) 使用字符串构造按钮对象;
    2) 把按钮添加到面板上;
    3) 用对应的颜色构造一个动作监听器;
    4) 注册动作监听器

    10.适配器类

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

     捕获窗口事件的监听器:

    WindowListener listener=…..;

    frame.addWindowListener(listener); 

    窗口监听器必须是实现WindowListener接口的类的一个对象,WindowListener接口中有七个方法,它们的名字是自解释的。

    鉴于代码简化的要求,对于有不止一个方法的AWT监听器接口都有一个实现了它的所有方法,但却不做任何工作的适配器类。

    例:WindowAdapter类。

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

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

    12.注册事件监听器

    可将一个Terminator对象注册为事件监听器:

    WindowListener listener=new Terminator();

    frame.addWindowListener(listener); 

    只要框架产生一个窗口事件,该事件就会传递给监听器对象。

    创建扩展于WindowAdapter的监听器类是很好的改进,但还可以进一步将上面语句也可简化为:

    frame.addWindowListener(new Terminator());

    13.动作事件

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

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

    14.动作接口及其类

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

     动作对象是一个封装下列内容的对象:
    –命令的说明:一个文本字符串和一个可选图标;
    –执行命令所需要的参数。

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

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

    在 动 作 事 件 处 理 应 用 中 , 可 以 直 接 扩 展AbstractAction 类 , 并 在 扩 展 类 中 实 现actionPerformed方法。

    15.鼠标事件

     鼠标事件
    – MouseEvent
     鼠标监听器接口
    – MouseListener
    – MouseMotionListener
     鼠标监听器适配器
    – MouseAdapter
    – MouseMotionAdapter

    用户点击鼠标按钮时,会调用三个监听器方法:
    – 鼠标第一次被按下时调用mousePressed方法;
    – 鼠标被释放时调用mouseReleased方法;
    – 两个动作完成之后,调用mouseClicked方法。
     鼠标在组件上移动时,会调用mouseMoved方法。

    如果鼠标在移动的时候还按下了鼠标,则会调用mouseDragged方法 

    鼠标事件返回值

    – 鼠标事件的类型是MouseEvent,当发生鼠标事件时:

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

    MouseEvent类中的重要方法
    – public int getX( );
    – public int getY( );
    – public Point getPoint( );
    – public int getClickCount( );

     

    第二部分:实验部分

    实验1:测试程序1(5分)

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

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

    lambda表达式简化程序;

     掌握JButton组件的基本API;

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

    ButtonTest.java

    package button;
    
    import java.awt.*;
    import javax.swing.*;
    
    /**
     * @version 1.35 2018-04-10
     * @author Cay Horstmann
     */
    public class ButtonTest
    {
       public static void main(String[] args)
       {
          EventQueue.invokeLater(() -> {
             var frame = new ButtonFrame();
             frame.setTitle("ButtonTest");
             frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
             frame.setVisible(true);
          });
       }
    }
    

      ButtonFrame.java

    package button;
    
    import java.awt.*;
    import java.awt.event.*;
    import javax.swing.*;
    
    /**
     * A frame with a button panel.
     */
    public class ButtonFrame extends JFrame
    {
       private JPanel buttonPanel;
       private static final int DEFAULT_WIDTH = 300;
       private static final int DEFAULT_HEIGHT = 200;
    
       public ButtonFrame()
       {      
          setSize(DEFAULT_WIDTH, DEFAULT_HEIGHT);
    
          //创建三个按钮
          var yellowButton = new JButton("Yellow");
          var blueButton = new JButton("Blue");
          var redButton = new JButton("Red");
    
          buttonPanel = new JPanel();
    
          //在面板上添加按钮
          buttonPanel.add(yellowButton);
          buttonPanel.add(blueButton);
          buttonPanel.add(redButton);
    
          //在框架上添加面板
          add(buttonPanel);
    
          // 创建按钮事件
          var yellowAction = new ColorAction(Color.YELLOW);
          var blueAction = new ColorAction(Color.BLUE);
          var redAction = new ColorAction(Color.RED);
    
          //关联事件与按钮
          yellowButton.addActionListener(yellowAction);
          blueButton.addActionListener(blueAction);
          redButton.addActionListener(redAction);
       }
    
       /**
        * An action listener that sets the panel's background color.
        */
       private class ColorAction implements ActionListener//ColorAction类作为ButtonFrame类的内部类,监听器类
       {
          private Color backgroundColor;
    
          public ColorAction(Color c)
          {
             backgroundColor = c;
          }
    
          public void actionPerformed(ActionEvent event)//对事件的响应
          {
             buttonPanel.setBackground(backgroundColor);
          }
       }
    }
    

      lamda表达式简化程序:

    public ButtonFrame() {
        setSize(DEFAULT_WIDTH, DEFAULT_HEIGHT);
        buttonPanel = new JPanel();
        makeButton("yellow", Color.yellow);
        makeButton("blue", Color.blue);
        makeButton("red", Color.red);
        add(buttonPanel);
    
    }
    
    protected void makeButton(String name,Color backgound) {
    	JButton button = new JButton(name);
        buttonPanel.add(button);
    //lamda表达式 button.addActionListener((event)->{ buttonPanel.setBackground(backgound); }); }

     

    实验1:测试程序2(5分)

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

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

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

     plafTest.java

    package plaf;
    
    import java.awt.*;
    import javax.swing.*;
    
    /**
     * @version 1.32 2015-06-1222222222222222222222222222
     * @author Cay Horstmann
     */
    public class PlafTest
    {
       public static void main(String[] args)
       {
          EventQueue.invokeLater(() -> {
             JFrame frame = new PlafFrame();
             frame.setTitle("PlafTest");
             frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
             frame.setVisible(true);
          });
       }
    }
    

      

     plafFrame.java

    package plaf;
    
    import javax.swing.JButton;
    import javax.swing.JFrame;
    import javax.swing.JPanel;
    import javax.swing.SwingUtilities;
    import javax.swing.UIManager;
    
    
    public class PlafFrame extends JFrame
    {
       private JPanel buttonPanel;
    
       public PlafFrame()
       {
          buttonPanel = new JPanel();
    
          UIManager.LookAndFeelInfo[] infos = UIManager.getInstalledLookAndFeels();//获得一个用于描述已安装的所有观感实现的对象数组
          for (UIManager.LookAndFeelInfo info : infos)
             makeButton(info.getName(), info.getClassName());//得到每一种观感的名字和类名
    
          add(buttonPanel);
          pack();//调整窗口大小
       }
    
       private void makeButton(String name, String className)
       {
          // 添加按钮
    
          JButton button = new JButton(name);
          buttonPanel.add(button);
    
          // 按钮动作
    
          button.addActionListener(event -> {
             try
             {
                UIManager.setLookAndFeel(className);//设置当前观感
                SwingUtilities.updateComponentTreeUI(this);//刷新全部组件集
                pack();//调整窗口大小
             }
             catch (Exception e)
             {
                e.printStackTrace();
             }
          });
       }
    }
    

      

      

     

     实验1:测试程序3(5分)

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

    掌握AbstractAction类及其动作对象;

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

    ActionTest.java

    package action;
    
    import java.awt.*;
    import javax.swing.*;
    
    /**
     * @version 1.34 2015-06-12
     * @author Cay Horstmann
     */
    public class ActionTest
    {
       public static void main(String[] args)
       {
          EventQueue.invokeLater(() -> {
             var frame = new ActionFrame();
             frame.setTitle("ActionTest");
             frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
             frame.setVisible(true);
          });
       }
    }
    

     

    ActionFrame.java

     

    package action;
    
    import java.awt.*;
    import java.awt.event.*;
    import javax.swing.*;
    
    /**
     * A frame with a panel that demonstrates color change actions.
     */
    public class ActionFrame extends JFrame
    {
       private JPanel buttonPanel;
       private static final int DEFAULT_WIDTH = 300;
       private static final int DEFAULT_HEIGHT = 200;
    
       public ActionFrame()
       {
          setSize(DEFAULT_WIDTH, DEFAULT_HEIGHT);
    
          buttonPanel = new JPanel();
    
          //动作
          var yellowAction = new ColorAction("Yellow", new ImageIcon("yellow-ball.gif"),Color.YELLOW);
          var blueAction = new ColorAction("Blue", new ImageIcon("blue-ball.gif"), Color.BLUE);
          var redAction = new ColorAction("Red", new ImageIcon("red-ball.gif"), Color.RED);
    
          //在按钮上添加动作
          buttonPanel.add(new JButton(yellowAction));
          buttonPanel.add(new JButton(blueAction));
          buttonPanel.add(new JButton(redAction));
    
          // add panel to frame
          add(buttonPanel);
    
          //关联names与击键Y、B、R
          InputMap inputMap = buttonPanel.getInputMap(JComponent.WHEN_ANCESTOR_OF_FOCUSED_COMPONENT);
          inputMap.put(KeyStroke.getKeyStroke("ctrl Y"), "panel.yellow");
          inputMap.put(KeyStroke.getKeyStroke("ctrl B"), "panel.blue");
          inputMap.put(KeyStroke.getKeyStroke("ctrl R"), "panel.red");
    
          //关联names与动作
          ActionMap actionMap = buttonPanel.getActionMap();
          actionMap.put("panel.yellow", yellowAction);
          actionMap.put("panel.blue", blueAction);
          actionMap.put("panel.red", redAction);
       }
       
       public class ColorAction extends AbstractAction
       {
          /**
           * Constructs a color action.
           * @param name the name to show on the button
           * @param icon the icon to display on the button
           * @param c the background color
           */
          public ColorAction(String name, Icon icon, Color c)//构造一个执行改变颜色命令的动作对象,存储这个命令的名称、图标和需要的颜色
          {
             putValue(Action.NAME, name);
             putValue(Action.SMALL_ICON, icon);
             putValue(Action.SHORT_DESCRIPTION, "Set panel color to " + name.toLowerCase());
             putValue("color", c);
          }
    
          public void actionPerformed(ActionEvent event)//改变颜色
          {
             var color = (Color) getValue("color");
             buttonPanel.setBackground(color);
          }
       }
    }
    

      

    实验1:测试程序4(5分)

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

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

    MouseTest.java

    package mouse;
    
    import java.awt.*;
    import javax.swing.*;
    
    /**
     * @version 1.35 2018-04-10
     * @author Cay Horstmann
     */
    public class MouseTest
    {
       public static void main(String[] args)
       {
          EventQueue.invokeLater(() -> {
             var frame = new MouseFrame();
             frame.setTitle("MouseTest");
             frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
             frame.setVisible(true);
          });
       }
    }
    

     MouseFrame.java

    package mouse;
    
    import javax.swing.*;
    
    /**
     * A frame containing a panel for testing mouse operations
     */
    public class MouseFrame extends JFrame
    {
       public MouseFrame()
       {
          add(new MouseComponent());
          pack();
       }
    }
    

      

    MouseComponent.java

    package mouse;
    
    import java.awt.*;
    import java.awt.event.*;
    import java.awt.geom.*;
    import java.util.*;
    import javax.swing.*;
    
    /**
     * A component with mouse operations for adding and removing squares.
     */
    public class MouseComponent extends JComponent
    {
       private static final int DEFAULT_WIDTH = 300;
       private static final int DEFAULT_HEIGHT = 200;
    
       private static final int SIDELENGTH = 10;
       private ArrayList<Rectangle2D> squares;//Rectangle2D 类描述通过位置 (x,y) 和尺寸 (w x h) 定义的矩形
       private Rectangle2D current; //包含鼠标光标的矩形 
      
    
       public MouseComponent()
       {
          squares = new ArrayList<>();//空列表
          current = null;
    
          addMouseListener(new MouseHandler());//鼠标监听器
          addMouseMotionListener(new MouseMotionHandler());//添加指定的鼠标移动侦听器,以接收发自此组件的鼠标移动事件
       }
    
       public Dimension getPreferredSize() 
       {
          return new Dimension(DEFAULT_WIDTH, DEFAULT_HEIGHT);
       }   
       
       public void paintComponent(Graphics g)
       {
          var g2 = (Graphics2D) g;
    
          //画矩形
          for (Rectangle2D r : squares)
             g2.draw(r);
       }
    
       /**
        * Finds the first square containing a point.
        * @param p a point
        * @return the first square that contains p
        */
       public Rectangle2D find(Point2D p)
       {
          for (Rectangle2D r : squares)
          {
             if (r.contains(p)) return r;//测试指定的 Point2D 是否在 Shape 的边界内
          }
          return null;
       }
    
       /**
        * Adds a square to the collection.
        * @param p the center of the square
        */
       public void add(Point2D p)
       {
          double x = p.getX();//返回该图形的X,Y坐标
          double y = p.getY();
    
          current = new Rectangle2D.Double(x - SIDELENGTH / 2, y - SIDELENGTH / 2,
             SIDELENGTH, SIDELENGTH);
          squares.add(current);
          repaint();
       }
    
       /**
        * Removes a square from the collection.
        * @param s the square to remove
        */
       public void remove(Rectangle2D s)
       {
          if (s == null) return;
          if (s == current) current = null;
          squares.remove(s);
          repaint();
       }
    
       private class MouseHandler extends MouseAdapter//鼠标监听器适配器
       {
          public void mousePressed(MouseEvent event)
          {
              //若鼠标光标不在之前的矩形内,则点击鼠标时,重新画一个矩形
             current = find(event.getPoint());
             if (current == null) add(event.getPoint());
          }
    
          public void mouseClicked(MouseEvent event)
          {
             // 若鼠标双击,则删除矩形
             current = find(event.getPoint());
             if (current != null && event.getClickCount() >= 2) remove(current);
          }
       }
    
       private class MouseMotionHandler implements MouseMotionListener
       {
          public void mouseMoved(MouseEvent event)
          {
             // 如果鼠标光标在矩形内,则将其设置为十字光标
    
             if (find(event.getPoint()) == null) setCursor(Cursor.getDefaultCursor());
             else setCursor(Cursor.getPredefinedCursor(Cursor.CROSSHAIR_CURSOR));
          }
    
          public void mouseDragged(MouseEvent event)
          {
             if (current != null)
             {
                int x = event.getX();
                int y = event.getY();
    
                //将当前矩形拖到(x,y)中心
                current.setFrame(x - SIDELENGTH / 2, y - SIDELENGTH / 2, SIDELENGTH, SIDELENGTH);
                repaint();
             }
          }
       }   
    }
    

      

     

     

    实验2:结对编程练习包含以下4部分:(20分)

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

    1)   程序设计思路简述;

           首先通过ArrayList类读入指定文件。再使用GIU类实现图形用户界面,使用jLable显示随机抽取的学生姓名,用actionPerformed方法实现在点击“开始”按钮这一事件,监听器类所实现的操作,并构造run方法,实现定时器,隔一定时间,随机显示下一个学生的姓名。

     

    2)   符合编程规范的程序代码;

    Test.java

    import java.awt.*;
    import javax.swing.*;
    public class Test
    {
       public static void main(String[] args)
       {
          EventQueue.invokeLater(() -> {
             nameRardom i = new nameRardom();
             i.setTitle("点名器");
             i.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
             i.setVisible(true);
      
          });
       }
    }
    

      GIU.java

    package 点名器;
    
    import java.awt.Color;
    import java.awt.Container;
    import java.awt.event.*;
    import java.io.*;
    import java.util.*;
    import java.util.Timer;
    
    import javax.swing.*;
    
    public class GIU extends JFrame {
        private ArrayList arrayList;
        {
        arrayList = new ArrayList<>();
        //读文件
        File file = new File("D:/2019studentlist.txt");
        FileInputStream fis;
        try {
            fis = new FileInputStream(file);
            InputStreamReader in = new InputStreamReader(fis);
            BufferedReader buf = new BufferedReader(in);
            String readLine;
            while ((readLine = buf.readLine())!=null) {
                arrayList.add(readLine);
                
            }
        } catch (FileNotFoundException e1) {
            
            e1.printStackTrace();
        } catch (IOException e1) {
           
            e1.printStackTrace();
        }
        }
        private JPanel a;
        private static final int DEFAULT_WIDTH = 500;
        private static final int DEFAULT_HEIGHT = 300;
        
        
    
        public GIU() {
            setSize(DEFAULT_WIDTH, DEFAULT_HEIGHT);
            a = new JPanel();
            a.setLayout(null);
            JLabel jLabel = new JLabel("随机点名器");
            JButton jButton = new JButton("开始");
            jLabel.setBounds(200, 50, 65, 40);
            jButton.setBounds(200, 90, 65, 40);
            
            
            
            jButton.addActionListener(new ActionListener() {
    
                Timer timer;
    
     
    
                public void actionPerformed(ActionEvent e) {
    
                    if (jButton.getText().equals("开始")) {
    
                        timer = new Timer();;
    
                        TimerTask timerTask = new TimerTask() {
    
                            public void run() {
                                jButton.setText("停止");
    
                                jButton.setBackground(Color.WHITE);
    
                                
                                jLabel.setText((String) arrayList.get((int) (Math.random() * 35)));
    
                            }
    
     
    
                        };
    
                        timer.schedule(timerTask, 0, 100);
    
                    }
    
                    if (jButton.getText().equals("停止")) {
    
                        timer.cancel();
    
                        jButton.setText("开始");
    
                        jButton.setBackground(Color.LIGHT_GRAY);
    
                    }
    
                }
    
            });
            
            
            
            
            a.add(jLabel);
            a.add(jButton);
            add(a);
    
        }
             
            
    }
    

      

    3)   程序运行功能界面截图;

    4)   结对过程描述,提供两人在讨论、细化和编程时的结对照片(非摆拍)。

     结对:刘兴瑞

    实验总结:(20分)

     在这周的学习中我们学习了图形界面事件处理技术的知识。首先掌握了事件处理的基本原理,并学会了事件处理的基本编程模型。学习了GUI界面组件观感设置方法与WindowAdapter类、AbstractAction类的用法 以及GUI程序中鼠标事件处理技术等知识。通过相应代码理解本章知识。通过老师、学长的讲解,理解了lamda表达式、内部类、匿名内部类、this处理程序的好处与不足,更加容易理解代码。本周的结队编程,对于读取文件方面以及对于Button方面的应用还是有些困难,但还是在不断的摸索,慢慢在学习、提升。

  • 相关阅读:
    httprunner运行报错问题:base url missed
    Locust性能模块浅谈
    如何对HTMLTestRunner 进行输出print 进行修改
    网易UI自动化测试工具Airtest中导入air文件中的方法
    如何在 idea 2019.3.4 中导入Github的项目并使用Git同步项目?
    Win10 Microsoft Store 微软商店 Error 0x00000193 解决方法
    读书笔记 |《计算机组成结构化方法》-01
    [MR] MapReduce 总结、回顾与吐槽
    [Git] 极简Git——关于Git的简要回顾
    [FlyWay] FlyWay工作原理
  • 原文地址:https://www.cnblogs.com/gwlg/p/11911140.html
Copyright © 2011-2022 走看看