zoukankan      html  css  js  c++  java
  • 201871020225-牟星源《面向对象程序设计(java)》第十三周学习总结

                                             201871020225-牟星源《面向对象程序设计(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程序中鼠标事件处理技术。

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

    一、事件处理

    Java中的事件主要有两种:

    组件类事件

    包括componentEvent、ContainerEvent、WindowEvent、FocusEvent、PaintEvent、MouseEvent共六大类,

    特点:它们均是当组件的状态发生变化时产生。

    动作类事件

    包括ActionEvent、TextEvent、AdjustmentEvent、ItemEvent共四类。

    特点:它们均对应用户的某一种功能性操作动作。

    注:Java中的事件类都包含在JDK的 Java.awt.event包中。

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

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

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

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

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

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

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

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

     

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

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

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

    注:事件:用户对程序的某一种功能性操作。

    7.事件编程:用户编程定义每个特定事件发生时程序应做出何种响应,并且这些响应代码会在对应的事件发生时由系统自动调用。

    8.事件委托授权处理模型

    JDK1.1以上版本实现了事件委托授权处理模型的机制。

    1事件源:产出事件的组件。

    2监听器:对组件所产生的事件作出具体响应的代吗,即事件产出与处理分别由两个不同类(它们可以分别放在不同的程序中)加以编程实现。

    3事件处理机制:AWT组件自身不编程处理相应的事件,面是交由事件监听器(它可以是组件所在的容器类或另外的Java程序类,只要它们实现了相关的事件监听器接口即可)处理(事件授权处理模型)。

    4事件处理的包:java.awt.event包,它提供AWT事件所需的类和接口

    ActionEvent类对应ActionListener接口;

    MouseEvent类对应MouseMotionListener接口和MouseListener接口;

    WindonEvent类对应WindonListener接口---即发生了XXXEvent类型的事件,那么处理该事件的接口为XXXListener);它们的父类为EventObject类。

    各个事件类的说明:

    EventObject:所有事件类的超类最重要的方法-- getSource(),返回产生某事件的对象

    AWTEvent:所有AWT事件类的超类最重要的方法-- getID(),返回某事件的ID号,事件的ID是一个整数,它指定事件的类型,例如按钮事件或鼠标点击事件

    ActionEvent:激活组件时发生的事件

    AdjustmentEvent:调节可调整的组件(如移动滚动条)时发生的事件

    ComponentEvent:操纵某组件时发生的一个高层事件

    ContainerEvent:向容器添加或删除组件时发生

    InputEvent:由某输入设备产生的一个高层事件

    ItemEvent:从选择项,复选框或列表中选择时发生

    KeyEvent:操作键盘时发生

    MouseEvent:操作鼠标时发生

    PaintEvent:描绘组件时发生的一个事件

    TextEvent:更改文本时发生

    WindowEvent:操作窗口时发生的事件,如最大化或最小化某一窗口。

    9.事件编程的基本原则:

    事件处理的类代码要对某一类事件加以处理,则应实现它们所对应的接口,并且给出该接口中定义的全部事件响应函数的功能实现(重写其函数体);然后在创建组件时注册该事件的监听器(响应者)。

    10.事件注册事件源通过对特定的事件进行注册,以指定该事件的监听器(响应者)是谁。

    11.事件注册函数:

    函数名由“add + 事件类型对应的监听器接口名称”组成;函数参数为监听器对象(实现事件响应的类的对象,如容器组件自身响应该事件,则监听器对象应用this代表)。

    Eg: public void add< listenerType >(< listenerType > ListenerObj)

    {

    }

    12.事件编程的基本规则:

    1组件对事件的响应形式:忽略它(本类不实现对应的监听器接口)或编程事件函数以处理它(可根据应用需要替换某一个组件的相应缺省事件处理函数,从而响应用户对该组件的操作。本类实现某类事件对应的监听器接口,并实现对应的响应函数),也可屏蔽它(将其事件响应函数体置空)。

    2事件响应类(监听器)可以实现多个监听器接口,以响应多组不同事件,从而可使同一个组件可以注册多种事件。

    3利用事件响应函数中的事件对象获取事件产生时的相关信息(event.getSource())事件源对象,event.getX(), event.getY(),事件产生时的鼠标位置,event.getActionCommand(),获取组件的字符串名称。

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

    14.动态事件:当特定组件动作(点击按钮)发生时,该组件生成此动作事件。该事件被传递给组件注册的每一个ActionListener对象,并调用监听器对象的actionPerformed方法以接受这类事件对象。能够触发事件动作的动作,主要包括:

    1)点击按钮

    2)双击一个列表中的选项

    3)选择菜单项

    4)在文本框中输入回车

    15.监听器接口的实现

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

    class MyListener implenments ActionListener

    {

    public void actionPerformed(ActionEvent event)

    {......}

    }

    16.命令按钮Jbutton主要API

    1)创建按钮对象

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

    a) JButton(String text):创建一个带文本的按钮。

    b) JButton(Icon icon) :创建一个带图标的按钮。

    c)JButton(String text, Icon icon) :创建一个带文本和图标

    的按钮

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

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

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

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

    ButtonTest.java中,各按钮需要同样的处理:

    1使用字符串构造按钮对象;

    2把按钮添加到面板上;

    3用对应的颜色构造一个动作监听器;

    4注册动作监听器

    18.适配器类

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

    1捕获窗口事件的监听器:

    WindowListener listener=…..;

    frame.addWindowListener(listener);

    2窗口监听器必须是实现WindowListener接口的

    类的一个对象,WindowListener接口中有七个

    方法,它们的名字是自解释的。

    19.鉴于代码简化的要求,对于有不止一个方法的AWT监听器接口都有一个实现了它的所有方法,但却不做任何工作的适配器类。例:WindowAdapter类。适配器类动态地满足了Java中实现监视器类的技术要求。

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

    20.注册事件监听器

    可将一个Terminator对象注册为事件监听器:WindowListener listener=new Terminator();frame.addWindowListener(listener);

    只要框架产生一个窗口事件,该事件就会传递给监听器对象。创建扩展于WindowAdapter的监听器类是很好的改进,但还可以进一步将上面语句也可简化为:frame.addWindowListener(new Terminator());

    21.动作事件

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

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

    22.动作接口及其类

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

    1 动作对象是一个封装下列内容的对象:

    –命令的说明:一个文本字符串和一个可选图标;

    –执行命令所需要的参数。

    2Action是一个接口,而不是一个类,实现这个接

    口的类必须要实现它的7个方法。

    3AbstractAction 类 实 现 了 Action 接 口 中 除actionPerformed方法之外的所有方法,这个类存储了所有名/值对,并管理着属性变更监听器。在 动 作 事 件 处 理 应 用 中 , 可 以 直 接 扩 展AbstractAction 类 , 并 在 扩 展 类 中 实 现

    actionPerformed方法。

    23.鼠标事件

    用户点击鼠标按钮时,会调用三个监听器方法:

    – 鼠标第一次被按下时调用mousePressed方法;

    – 鼠标被释放时调用mouseReleased方法;

    – 两个动作完成之后,调用mouseClicked方法。

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

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

    2鼠标事件返回值

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

    第二部分:实验部分

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

    实验1:测试程序1

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

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

    3lambda表达式简化程序;

    4掌握JButton组件的基本API;

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

    具体代码如下:

     ButtonFrame:

    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 panel to frame
          add(buttonPanel);
     
          // create button actions
          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
       {
          private Color backgroundColor;
     
          public ColorAction(Color c)
          {
             backgroundColor = c;
          }
     
          public void actionPerformed(ActionEvent event)
          {
             buttonPanel.setBackground(backgroundColor);
          }
       }
    }
    ButtonTest:
    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);
          });
       }
    }

    简化后代码:

    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);
            buttonPanel = new JPanel();
            makeButton("yellow", Color.yellow);
            makeButton("blue", Color.blue);
            makeButton("red", Color.red);
            add(buttonPanel);
        }
        protected void makeButton(String name,Color backgound) {
            // create buttons
            JButton button = new JButton(name);
            // add buttons to panel
            buttonPanel.add(button);
            button.addActionListener((e)->{
            buttonPanel.setBackground(backgound);
            });
        }
    }

    运行结果如下:

                     

    实验1:测试程序2

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

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

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

    具体代码如下:

     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();
       }
     
       /**
        * 创建一个按钮来更改可插入的外观.
        * @param name the button name
        * @param className the name of the look-and-feel class
        */
       private void makeButton(String name, String className)
       {
          //添加按钮到面板
     
          JButton button = new JButton(name);
          buttonPanel.add(button);
     
          //设置按钮要进行的操作
     
          button.addActionListener(event -> {
             // 按钮操作结果: 切换到新的外观
             try //可能出错的代码放入try子句中
             {
                UIManager.setLookAndFeel(className);
                SwingUtilities.updateComponentTreeUI(this);
                pack();
             }
             catch (Exception e)
             {
                e.printStackTrace();
             }
          });
       }
    }

    package plaf;

     
    import java.awt.*;
    import javax.swing.*;
    /**
     * @version 1.32 2015-06-12
     * @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);
          });
       }
    }

    运行结果如下:

     

     

     

     

     

    实验1:测试程序3

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

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

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

    具体代码为:

    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);
     
          // add buttons for these actions
          buttonPanel.add(new JButton(yellowAction));
          buttonPanel.add(new JButton(blueAction));
          buttonPanel.add(new JButton(redAction));
     
          add(buttonPanel);
     
       // 将Y,B,R这些键与名称联系起来
          /*
           *可以使用getInputMap方法从组件中得到输入映射
           * WHEN_ANCESTOR_OF_FOCUSED_COMPONENT条件意味着在当前组件包含了拥有键盘焦点的组件时会查看这个映射
           */
          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");
     
          // associate the names with actions
          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)
          {
            //将所有信息存储在AbstractAction类提供的名/值对表中
             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)
          {
              //获取名/值对表中名为color的值并将其强制转换为颜色对象
             var color = (Color) getValue("color");
             buttonPanel.setBackground(color);
          }
       }
    }
     
    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);
          });
       }
    }
    运行结果为:

     

    实验1:测试程序4

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

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

    代码为:

    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;//声明一个正方形集合
       private Rectangle2D current; // Java类库中用来描述矩形的类,它的对象可以看作是一个矩形
    
       public MouseComponent()
       {
          squares = new ArrayList<>();
          current = null;
    
          addMouseListener(new MouseHandler());
          //添加一个我们实现的类,这个类继承了监测鼠标点击情况的MouseListener
          addMouseMotionListener(new MouseMotionHandler());
          // 添加另一个实现类,这个类继承了监测鼠标移动情况的MouseMotionListener
    
       }
    
       public Dimension getPreferredSize() 
       {
          return new Dimension(DEFAULT_WIDTH, DEFAULT_HEIGHT);
       }   
       
       public void paintComponent(Graphics g)
       {
          Graphics2D g2 = (Graphics2D) g;// 转换为我们需要使用的类
    
          // draw all squares
          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;
          }
          return null;
       }
    
       /**
        * Adds a square to the collection.
        * @param p the center of the square
        */
       public void add(Point2D p)
       {
          double x = p.getX();
          double y = p.getY();
        //获取x和y的坐标
          current = new Rectangle2D.Double(x - SIDELENGTH / 2, y - SIDELENGTH / 2,
             SIDELENGTH, SIDELENGTH);
        //用获得的坐标和既定的边长构建一个新的正方形,并将其赋值给current
    
          squares.add(current);//将current添加到squares队列中
          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;
        //如果要移除的内容和current正指向的内容相同,则将current清空
        //避免发生不必要的错误
          
          
          squares.remove(s);//将s从squares的列表中直接删去
          repaint();//重绘component的方法
       }
    
       private class MouseHandler extends MouseAdapter
       {
          public void mousePressed(MouseEvent event)//鼠标按下方法
          {
             // 如果光标不在正方形中,则添加一个新的正方形
             current = find(event.getPoint());
          // 将鼠标单击的这个点的坐标的对象赋给current
             if (current == null)
                //如果这个点没有对象,当前指向空的位置
                 add(event.getPoint());
          }
    
          public void mouseClicked(MouseEvent event)//鼠标按下方法
          {
             // 如果光标不在正方形中,则添加一个新的正方形中
             current = find(event.getPoint());
             //将鼠标单击的这个点的坐标的对象赋给current
             if (current != null && event.getClickCount() >= 2) remove(current);
          }
       }
    
       private class MouseMotionHandler implements MouseMotionListener
       {
          public void mouseMoved(MouseEvent event)
          {
             // set the mouse cursor to cross hairs if it is inside a rectangle
    
             if (find(event.getPoint()) == null) setCursor(Cursor.getDefaultCursor());
             else setCursor(Cursor.getPredefinedCursor(Cursor.CROSSHAIR_CURSOR));
          }
    
          public void mouseDragged(MouseEvent event)
          {
             if (current != null)
             {
                 //因为在调用这个方法之前肯定会调用点击鼠标的方法
                 //所以我们直接判断:如果现在current不为空
                 //像素(强制转换为int) 
                int x = event.getX();
                int y = event.getY();
               //获取带坐标
                
                
                // drag the current rectangle to center it at (x, y)
                current.setFrame(x - SIDELENGTH / 2, y - SIDELENGTH / 2, SIDELENGTH, SIDELENGTH);
                //最后在鼠标放下时进行图形绘制
                repaint();
             }
          }
       }   
    }

     

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

    结对编程练习包含以下4部分:

    1) 程序设计思路简述;

     点名器需要有一个定时器,还要有一个循环,设计一个GUI图形界面,读取文件里面学生的姓名,在actionPerformed方法中,当jButton的内容为"begin"时,启动定时器,利用随机数来得到学生的姓名,当jButton的内容为"stop"时,调用Timer类对象的cancel方法停用定时器,由此得到。

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

    package button;
    import java.awt.Color;
    import java.awt.event.ActionEvent;
    import java.awt.event.ActionListener;
    import java.io.BufferedInputStream;
    import java.io.BufferedReader;
    import java.io.File;
    import java.io.FileInputStream;
    import java.io.FileNotFoundException;
    import java.io.IOException;
    import java.io.InputStreamReader;
    import java.io.StringBufferInputStream;
    import java.util.ArrayList;
    import java.util.Timer;
    import java.util.TimerTask;
    import javax.swing.JButton;
    import javax.swing.JFrame;
    import javax.swing.JLabel;
    import javax.swing.JPanel;
    public class ButtonFrame extends JFrame {
         private JPanel buttonPanel;
         private static final int DEFAULT_WIDTH = 600;
         private static final int DEFAULT_HEIGHT = 500;
         private JButton jButton;
         private ArrayList<String> arrayList;
     
         public ButtonFrame() {
             setSize(DEFAULT_WIDTH, DEFAULT_HEIGHT);
             buttonPanel = new JPanel();
             buttonPanel.setLayout(null);
             buttonPanel.setBackground(Color.blue);
             add(buttonPanel);
             jButton = new JButton("Begin");
             jButton.setBackground(Color.blue);
             jButton.setBounds(200, 100, 120, 60);
             jButton.setBounds(200, 240, 120, 60);
             arrayList = new ArrayList<>();
             //读文件
             File file = new File("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) {
                 // TODO Auto-generated catch block
                 e1.printStackTrace();
             } catch (IOException e1) {
                 // TODO Auto-generated catch block
                 e1.printStackTrace();
             }
            
             jButton.addActionListener(new ActionListener() {
                Timer timer;
     
                 public void actionPerformed(ActionEvent e) {
                     if (jButton.getText().equals("Begin")) {
                        timer = new Timer();;
                         TimerTask timerTask = new TimerTask() { 
                          public void run() {
                                 jButton.setText("Stop");
                                 jButton.setBackground(Color.red);
                                 jButton.setText(arrayList.get((int) (Math.random() * 35)));
                             }
                          };
                        timer.schedule(timerTask, 0, 20);
                     }
                     if (jButton.getText().equals("Stop")) {
                         timer.cancel();
                         jButton.setText("Begin");
                         jButton.setBackground(Color.blue);
                     }
                 }
             });
             buttonPanel.add(jButton);
             buttonPanel.add(jButton);
             add(buttonPanel);
     
         }
     }

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

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

    第三部分:实验总结:

     本次实验中,主要学到了事件源,事件监听器,和事件对象,以及动作事件,在事件监听器中,必须要实现actionPerform()方法,用来接收事件对象。创建按钮对象中JButton类的构造方法很常用,也很重要。用匿名内部类和lambda表达式简化程序是一个很重要的方法,我掌握的一般,会继续努力。观感和鼠标事件我觉得比前面的难一点,通过测试程序和看书,还是知道了一点点,最后的结对编程很难,通过网上查找,寻求其他同学的帮助,然后还有自己琢磨,也还差不多了,但是问题还是很多,我也会自己抓紧的。

  • 相关阅读:
    Mysql查漏补缺
    RabbitMQ学习笔记
    memcache学习笔记
    Redis问题整理
    JedisCluster获取key所在的节点
    JavaSE编程题
    IDEA快捷键 日常整理
    Idea 常用快捷键列表
    【C++】 构造函数为什么不能声明为虚函数,析构函数可以
    【算法笔记】买卖股票问题--DP/贪心算法
  • 原文地址:https://www.cnblogs.com/muxingyuan/p/11930786.html
Copyright © 2011-2022 走看看