zoukankan      html  css  js  c++  java
  • 201871010110-李华《面向对象程序设计(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分)

     11.1 事件处理模型

    事件源(event source):能够产生事件的对象都可

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

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

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

    11.1.1处理按钮点击事件

      1.对于GUI的应用程序来说,事件处理是必不可少的,因此我们需要熟练地掌握事件处理模型。对于事件我们需要了解两个名词:事件源对象与监听器对象。从字面上我们就可以理解个大概,下面我们系统说明一下:监听器对象是一个实现了特定监听器接口(listener interface)的类的实例,事件源是一个能够注册监听器对象并发送事件对象的对象,事件发生时,事件源将事件对象传递给所有注册的监听器,监听器对象将利用事件对象中的信息决定如何对事件做出相应

      首先我们将监听器对象注册给事件源对象,这样当事件触发时系统便可以通过事件源访问相应的监听器。如下图:

                                                                

      当事件源触发事件后,系统便将事件的相关信息封装成相应类型的事件对象,并将其发送给注册到事件源的相应监听器。如下图:

                                                     

      当事件对象发送给监听器后,系统调用监听器的相应事件处理方法对事件进行处理,也就是做出响应。如下图:

                                                                       

    注意:监听器与事件源之间是“多对多”的关系。

    11.1.2简洁的指定监听器

    监听器对象就是一个实现了特定监听器接口的类的实例,那么监听器接口就是我们所关心的问题了。在监听器接口的最顶层接口是java.util.EventListener,这个接口是所有事件侦听器接口必须扩展的标记接口。感到诧异的是这个接口完全是空的,里面没有任何的抽象方法的定义,查看源代码里面空空如也啊!

    事件监听器类(监听器对象所属的类)必须实现事件监听器接口或继承事件监听器适配器类。
    事件监听器接口定义了处理事件必须实现的方法。
    事件监听器适配器类是对事件监听器接口的简单实现。目的是为了减少编程的工作量。
      事件监听器的接口命名方式为:XXListener,而且,在java中,这些接口已经被定义好了。用来被实现,它定义了事件处理器(即事件处理的方法原型,这个方法需要被重新实现)。

    例如:ActionListener接口、MouseListener接口、WindowListener接口、KeyListener接口、ItemListener接口、MouseMotionListener接口、FocusListener接口、ComponentListener接口等

    11.1.3改变观感

    Swing程序默认使用Metal观感,采用两种方式改变观感。
    第一种:在Java安装的子目录jre/lib下的文件swing.properties中,将属性swing.defaultlaf设置为所希望的观感类名。
                  swing.defaultlaf=com.sun.java.swing.plaf.motif.MotifLookAndFeel
    第二种:调用静态的UIManager. setLookAndFeel方法,动态地改变观感,提供所想要的观感类名,再调用静态方法SwingUtilities.updateComponentTreeUI来刷新全部的组件集。
    11.1.4适配器类

    1.当程序用户试图关闭一个框架窗口时,JFrame对象就是WindowEvent的事件源。
      捕获窗口事件的监听器:WindowListener listener=...frame.addWindowListener(listener); 
      窗口监听器必须是实现WindowListener接口的类的一个对象,WindowListener接口中有七个方法,它们的名字是自解释的。

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

    3.扩展WindowAdapter类,继承六个空方法,并覆盖WindowClosing()方法:
         class Terminator extends WindowAdapter{
         public void windowClosing(WindowEvente){
         System.exit(0);}}

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

    11.2 动作

      动作事件(ActionEvent):当特定组件动作(点击按钮)发生时,该组件自动生成此动作事件。
    该事件被传递给组件注册的每一个ActionListener对象,并调用监听器对象的actionPerformed方法以接收这类事件对象。
    动作事件主要包括:(1) 点击按钮  (2) 双击一个列表中的选项;(3) 选择菜单项;(4) 在文本框中输入回车。

    11.2.1动作接口及其类

    1.Swing包提供了非常实用的机制来封装动作命令,并将它们连接到多个事件源,这就是Action接口动作对象是一个封装下列内容的对象:命令的说明:一个文本字符串和一个可选图标;执行命令所需要的参数。

    2.Action是一个接口,而不是一个笑,实现这个按口的类必须要实现它的7个方法。
    3.AbstractAction 类 实 现 了 Action 接口 中 除actionPerformed方法之外的所有方法,这个类存储了所有名/值对,并管理着属性变更监听器。
    4.在动作事件处理应用中,可以直接扩展AbstractAction 类,并在扩展类中实现actionPerformed方法。

    11.2.2击键关联映射

    1.将一个动作对象添加到击键中,以便让用户敲击键盘命令来执行这个动作。
    2.将动作与击键关联起来,需生成KeyStroke类对象。KeyStroke ctrBKey=KeyStroke.getKeyStroke(“Ctrl B”);
    3.将击键与动作对象关联起来的方式(桥梁:动作键对象描述字符串)
    11.3 鼠标事件

    1.鼠标事件一 MouseEvent
       鼠标监听器接口      - MouseListener     -MouseMotionListener
       鼠标监听器适配器    MouseAdapter        MouseMotionAdapter

       鼠标点击监听器接口

      public interface WindowListener{
         void windowOpened(WindowEvent e)
         void windowClosing(WindowEvent e);
         void windowClosed(WindowEvente);
         void windowlconified(WindowEvent e);
         void windowDeiconified(WindowEvent e);
         void windowActivated(WindowEvent e);
         void windowDeactivated(WindowEvent e);
         }

    2.用户点击鼠标按钮时,会调用三个监听器方法:标第一次被按下时调用mousePressed方法;鼠标被释放时调用mouseReleased方法;
       两个动作完成之后,调用mouseClicked方法。鼠标在组件上移动时,会调用mouseMoved方法。
       如果鼠标在移动的时候还按下了鼠标,则会调用mouseDragged方法。
    3.鼠标事件返回值
       鼠标事件的类型是MouseEvent,当发生鼠标事件时:
      MouseEvent类自动创建一个事件对象,以及事件发生位置的x和y坐标,作为事件返回值。
      MouseEvent类中的重要方法 

       一 public int getX( );
          public int getY( );
          public Point getPoint();
          public int getClickCount();

    11.4AWT事件继承层次

    11.4.1AWT中的事件分类

    AWT将事件分为低级(low-level)事件和语义(semantic)事件。
    语义事件:表达用户动作的事件。例:点击按钮(ActionEvent)。

    低级事件:形成语义事件的事件。例:点击按钮,包含了按下鼠标、连续移动鼠标、抬起鼠标事件。

    AWT事件处理机制的概要:

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

     事件源:是一个能够注册监听器对象并发送事件对象的对象。

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

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

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

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

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

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

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

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

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

    (1) 点击按钮

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

    (3) 选择菜单项;

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

    第二部分:实验部分

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

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

    实验代码:

    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);
    
          // create buttons
          JButton yellowButton = new JButton("Yellow");
          JButton blueButton = new JButton("Blue");
          JButton redButton = new JButton("Red");
         //通过在按钮构造器中指定一个标签字符串,一个图标或两项都指定来创建一个按钮
          buttonPanel = new JPanel();
    
          // add buttons to panel
          buttonPanel.add(yellowButton);
          buttonPanel.add(blueButton);
          buttonPanel.add(redButton);
    
          // add panel to frame
          add(buttonPanel);
          //调用add方法将按钮添加到面板中
          
          
          // create button actions  为每种颜色构造一个对象
          ColorAction yellowAction = new ColorAction(Color.YELLOW);
          ColorAction blueAction = new ColorAction(Color.BLUE);
          ColorAction redAction = new ColorAction(Color.RED);
    
          // associate actions with buttons 将动作与按钮关联
          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);
          }
       }
    }
    

      

    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);
          });
       }
    }
    

      

    实验运行结果:

                    

    lambda表达式简化程序;

    代码如下:

    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("黄色", Color.yellow);
            makeButton("蓝色", Color.blue);
            makeButton("红色", 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);
            });
            
        }
    }
    /**create buttons
    JButton yellowButton = new JButton("Yellow");
    JButton blueButton = new JButton("Blue");
    JButton redButton = new JButton("Red");
    //通过在按钮构造器中指定一个标签字符串,一个图标或两项都指定来创建一个按钮
    buttonPanel = new JPanel();
    
    // add buttons to panel
    buttonPanel.add(yellowButton);
    buttonPanel.add(blueButton);
    buttonPanel.add(redButton);
    
    // add panel to frame
    add(buttonPanel);
    //调用add方法将按钮添加到面板中
    
    
    // create button actions  为每种颜色构造一个对象
    ColorAction yellowAction = new ColorAction(Color.YELLOW);
    ColorAction blueAction = new ColorAction(Color.BLUE);
    ColorAction redAction = new ColorAction(Color.RED);
    
    // associate actions with buttons 将动作与按钮关联
    yellowButton.addActionListener(yellowAction);
    blueButton.addActionListener(blueAction);
    redButton.addActionListener(redAction);
    }
    
    
    //设置面板背景颜色的动作监听器  将面板的背景颜色设置为指定的颜色
    private class ColorAction implements ActionListener
    {
    private Color backgroundColor;
    
    public ColorAction(Color c)
    {
       backgroundColor = c;
    }
    //颜色存储在监听器中
    public void actionPerformed(ActionEvent event)
    {
       buttonPanel.setBackground(backgroundColor);
    }
    }
    }**/

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

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

    代码如下:

    package plaf;
    
    import javax.swing.JButton;
    import javax.swing.JFrame;
    import javax.swing.JPanel;
    import javax.swing.SwingUtilities;
    import javax.swing.UIManager;
    
    /**
    * A frame with a button panel for changing 1ook-and-feel
    */
    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();
       } 
    /**Makes a button to change the pluggable look-and-feel.
    *@param name the button name
    *@param className the name of the look-and-feel class
    */
       
    private void makeButton(String name, String className)
    {
        // add button to panel
       JButton button =new JButton(name);
       buttonPanel.add(button);
       buttonPanel.add(button);
       // set button action
       button.addActionListener(event -> {
       // button action: switch to the new look-and-feel
       //捕捉异常
       try
       {   //设置观感
    	   UIManager.setLookAndFeel(className);
           SwingUtilities.updateComponentTreeUI(this);//刷新全部的组件
           pack();
       }
       catch (Exception e)
       {
         e.printStackTrace();
       }
       });
    }
    }  

    运行结果:

             

                                           

             

     

      

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

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

    代码如下:

    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();
    
          // define actions   创建类的三个对象
          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 panel to frame     将面板添加到框架
          add(buttonPanel); 
    
          // associate the Y, B, and R keys with 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");
    
          // 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
       {       // 构造器设置名/值对,actionPerformed方法执行改变颜色的动作
          /**
           * 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);
          }
       }
    }
    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:测试程序1(5分)

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

    代码如下:

    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);
          });
       }
    }
    

      

    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();
       }
    }    //程序清单
    

      

    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; // the square containing the mouse cursor
                                         //包含鼠标光标的正方形
       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;
    
          // 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();
    
          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)
          {
             // add a new square if the cursor isn't inside a square
             current = find(event.getPoint());  //如果光标位于一个正方形的旁边,则添加一个新的正方形
             if (current == null) 
            	 add(event.getPoint());    //鼠标点击在所有小方块的像素之外
          }
    
          public void mouseClicked(MouseEvent event)
          {
             // remove the current square if double clicked  如果双击,删除当前方块
             current = find(event.getPoint());
             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)
             {
                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:结对编程练习包含以下4部分:(20分)

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

    1 点名器启动界面图                                    2 点名器随机显示姓名界面

                                     

    1)   程序设计思路简述;

        首先定义数组,用txt文件存储学生姓名信息,文件读取到数组,用ActionListener接口实现按钮控制,并且监听器要定义一个actionPerformed方法,该方法接收ActionEvent对象参数,按钮产生一个动作事件,动作用getText和setText方法调用,用户点击按钮,当为“开始”时,timer调用 start() 方法,为“停止”时,timer调用stop()方法,还有一些颜色设置。当随机抽取一个学生姓名后,把姓名显示到GUI界面上。

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

    package dianming;
    
    
    import java.awt.Color;
    import java.awt.Dimension;
    import java.awt.FlowLayout;
    import java.awt.Label;
    import java.awt.event.ActionEvent;
    import java.awt.event.ActionListener;
    import java.io.BufferedReader;
    import java.io.File;
    import java.io.FileInputStream;
    import java.io.IOException;
    import java.io.InputStreamReader;
    import java.util.ArrayList;
    
    import javax.swing.JButton;
    import javax.swing.JFrame;
    import javax.swing.Timer;
    
    public class Rollcall 
    {
        public static void main(String args[]) 
        {
            try {
                Dmq dmq = new Dmq();
                dmq.lab.setText("随机点名器");
                dmq.setTitle("点名器");
            } catch (IOException e) 
            {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
        }
    }
    
    class Dmq extends JFrame 
    {
        final Label lab = new Label();
        ArrayList<String> namelist = new ArrayList<String>();
    
        public Dmq() throws IOException 
        {
            File file = new File("src/2019studentlist.txt");
            FileInputStream fis = new FileInputStream(file);
            InputStreamReader isr = new InputStreamReader(fis, "GBK");
            BufferedReader br = new BufferedReader(isr);
            String line = "";
            while ((line = br.readLine()) != null) 
            {
                if (line.lastIndexOf("---") < 0) 
                {
                    namelist.add(line);
                }
            }
            setBounds(550, 300, 200, 100);
            final Timer timer = new Timer(50, new ActionListener() 
            {
                public void actionPerformed(ActionEvent e) 
                {
                    lab.setText(namelist.get((int) (Math.random() * namelist.size())));
                }
            });
    
            JButton jbutton = new JButton("开始");
            jbutton.setPreferredSize(new Dimension(220,80));
            lab.setPreferredSize(new Dimension(110,60));
            jbutton.addActionListener(new ActionListener() 
            {
                public void actionPerformed(ActionEvent e) 
                {
                    JButton jbutton = (JButton) e.getSource();
                    if (jbutton.getText().equals("开始")) 
                    {
                        jbutton.setText("停止");
                        timer.start();
                        
             
                    } else if (jbutton.getText().equals("停止")) 
                    {
                        jbutton.setText("开始");
                        timer.stop();
                       
                    }
    
                }
            });
            jbutton.setBounds(30,30,300,100);
            jbutton.setBackground(Color.pink);
            lab.setBackground(Color.pink);
            this.setLayout(new FlowLayout());
            this.add(lab);
            this.add(jbutton);
            this.setSize(300,300);
            this.setVisible(true);
            this.setDefaultCloseOperation(EXIT_ON_CLOSE);
            br.close();
        }
    
    }  

    运行结果;

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

    实验总结:(20分)

              这一周学习了第十一章的内容,从掌握事件处理的基本原理开始,理解了它的用途,在基础性的概念理解之后,对这一章有了一定的认识,然后学习了AWT事件模型的工作机制,掌握的不是特别清楚,但是经过示例程序的编译和运行之后,也有了很大提升,然后学习了事件处理的基本编程模型,了解GUI界面组件观感设置方法;学习时知识点较多,故还需要自己在课后花更多的时间理解和记忆,最后在掌握了WindowAdapter类、AbstractAction类的用法后, 学习了GUI程序中鼠标事件处理技术,对利用java语言设计小型界面有了更多的学习,在最后一章学习后,经过学长的讲解,对这一章有了更深的理解,在做最后一个编程题时也发现自己的许多问题,也一定要通过自己的努力弥补不足。

  • 相关阅读:
    无法通过给定的扩展名确定设备类型
    biuld example_osgviewerGLUT遇到的error Link2019
    OpenGL渲染流水线
    设计模式总目录
    删除thumbs.db是提示正在使用
    COM技术内幕第十章笔记EXE中的服务器
    在高低版本之间互导max文件,以fbx格式为载体尤佳。
    参数值传递的本质
    VS 为什么要检查行尾的一致性?
    vs2005中的GL文件
  • 原文地址:https://www.cnblogs.com/LH-18110/p/11920562.html
Copyright © 2011-2022 走看看