201271050130-滕江南-《面向对象程序设计(java)》第十三周学习总结

 

201271050130-滕江南-《面向对象程序设计(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程序中鼠标事件处理技术。

 

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

第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) 事件对象封装了事件源与监听器彼此通信的事件 信息。在必要的时候,可以对传递给监听器对象的 事件对象进行分析。

 

第二部分:实验目的与要求

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

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

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

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

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

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

1、实验内容和步骤

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

测试程序1:

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

package test;

import java.awt.*;
import java.awt.event.*;
import javax.swing.*;

/**
 * 带按钮面板的框架
 */

 
public class ButtonFrame extends JFrame
{
   private JPanel buttonPanel;
   private static final int DEFAULT_WIDTH = 500;
   private static final int DEFAULT_HEIGHT = 600;

   public ButtonFrame()
   {      
      setSize(DEFAULT_WIDTH, DEFAULT_HEIGHT);

      // 创建三个按钮 
//      JButton yellowButton = new JButton("Yellow");
//      JButton blueButton = new JButton("Blue");
//      JButton redButton = new JButton("Red");

      buttonPanel = new JPanel();

       // 向面板添加按钮
//      buttonPanel.add(yellowButton);
//      buttonPanel.add(blueButton);
//      buttonPanel.add(redButton);

      // 将面板添加到帧
      add(buttonPanel);

//       创建按钮动作
//      ColorAction yellowAction = new ColorAction(Color.YELLOW);
//      ColorAction blueAction = new ColorAction(Color.BLUE);
//      ColorAction redAction = new ColorAction(Color.RED);
//
//       用按钮关联动作
//      yellowButton.addActionListener(yellowAction); 
//      blueButton.addActionListener(blueAction);
//      redButton.addActionListener(redAction);
   
   MakeButton("黄色",Color.yellow); 
   MakeButton("蓝色",Color.blue); 
   MakeButton("红色",Color.red);
   }
   public void MakeButton(String name , Color backgroundColor) 
   { 
       JButton button=new JButton(name); 
       buttonPanel.add(button); 
//       ColorAction action=new ColorAction(backgroundColor); 
//       button.addActionListener(action); 
       button.addActionListener(new ActionListener() 
       { 
           public void actionPerformed(ActionEvent event) 
           {           
               buttonPanel.setBackground(backgroundColor); 
               } 
           });

   } 
   

   /**
    * 设置面板背景颜色的动作侦听器
    */
   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.34 2015-06-12
 * @author Cay Horstmann
 */
public class ButtonTest
{
   public static void main(String[] args)
   {
      EventQueue.invokeLater(() -> {
         JFrame frame = new ButtonFrame();
         frame.setTitle("ButtonTest");
         frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
         frame.setVisible(true);
      });
   }
}

  

测试程序2:在elipse IDE中调试运行教材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;

/**
 * 带有按钮面板的框架,用于改变外观和感觉
 */
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 命名按钮名称
    * @param 类名:外观类的名称
    */
   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();
         }
      });
   }
}

  

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

  

测试程序3:

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

package action;

import java.awt.*;
import javax.swing.*;

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

  

package action;

import java.awt.*;
import java.awt.event.*;
import javax.swing.*;

/**
 * 具有显示颜色变化动作的面板的框架
 */
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();

      // 定义动作
      Action yellowAction = new ColorAction("Yellow", new ImageIcon("yellow-ball.gif"),
            Color.YELLOW);
      Action blueAction = new ColorAction("Blue", new ImageIcon("blue-ball.gif"), Color.BLUE);
      Action 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(buttonPanel);

      // 将Y、B和R键与名称关联
      InputMap imap = buttonPanel.getInputMap(JComponent.WHEN_ANCESTOR_OF_FOCUSED_COMPONENT);
      imap.put(KeyStroke.getKeyStroke("ctrl Y"), "panel.yellow");
      imap.put(KeyStroke.getKeyStroke("ctrl B"), "panel.blue");
      imap.put(KeyStroke.getKeyStroke("ctrl R"), "panel.red");

      // 把名字和动作联系起来
      ActionMap amap = buttonPanel.getActionMap();
      amap.put("panel.yellow", yellowAction);
      amap.put("panel.blue", blueAction);
      amap.put("panel.red", redAction);
   }
   
   public class ColorAction extends AbstractAction
   {
      /**
       * 构造颜色动作。
       * @param 在按钮上显示要显示的名称
       * @param 图标按钮上显示的图标
       * @param 背景颜色
       */
      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)
      {
         Color c = (Color) getValue("color");
         buttonPanel.setBackground(c);
      }
   }
}

  

 

测试程序4:

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

 

package mouse;

import java.awt.*;
import javax.swing.*;

/**
 * @version 1.34 2015-06-12
 * @author Cay Horstmann
 */
public class MouseTest
{
   public static void main(String[] args)
   {
      EventQueue.invokeLater(() -> {
         JFrame frame = new MouseFrame();
         frame.setTitle("MouseTest");
         frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
         frame.setVisible(true);
      });
   }
}

  

package mouse;

import javax.swing.*;

/**
 * 包含用于测试鼠标操作的面板的框架
 */
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.*;

/**
 *一个带有鼠标操作的用于添加和删除正方形的组件。
 */
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; // 包含鼠标光标的正方形

   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)
   {
      Graphics2D g2 = (Graphics2D) g;

      // 绘制所有正方形
      for (Rectangle2D r : squares)
         g2.draw(r);
   }

   /**
    * 找到包含一个点的第一个方块。
    * @param P—A点
    * @return 包含P的第一个正方形
    */
   public Rectangle2D find(Point2D p)
   {
      for (Rectangle2D r : squares)
      {
         if (r.contains(p)) return r;
      }
      return null;
   }

   /**
    * 向集合中添加正方形。
    * @param 新闻中心
    */
   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();
   }

   /**
    * 从集合中移除正方形。
    * @param S方移除
    */
   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:结对编程练习

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

package Roll_call_device;


import java.awt.Color;
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/studentnamelist.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, 270, 200, 150);
        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.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, 30, 30);
        lab.setBackground(new Color(255, 255, 255));
        this.setLayout(new FlowLayout());
        this.add(lab);
        this.add(jbutton);
        this.setSize(300, 200);
        this.setVisible(true);
        this.setDefaultCloseOperation(EXIT_ON_CLOSE);
        br.close();
    }

}

  

 

第三部分:总结

   本章主要学习了事件处理的基本原理,理解其用途;掌握AWT事件模型的工作机制; 掌握事件处理的基本编程模型;了解GUI界面组件观感设置方法; 掌握WindowAdapter类、AbstractAction类的用法; 掌握GUI程序中鼠标事件处理技术。由于自己的基础等各方面的原因,以及前面知识与后面知识的衔接等原因,这一章的学习对于我来说还是相比较上一章来说有较大的困难的最后的编程题是在舍友的帮助下完成。在过程中也学习到了很多,很多时候独立完成作业比较困难没有思路,两个人相互交流讨论有助学习进步。

 

  

 

 

 

 

 

 

 

posted @ 2019-11-25 11:10  滕江南  阅读(92)  评论(0编辑  收藏  举报