201771010113 李婷华 《面向对象程序设计(Java)》第十三周总结

一.理论知识部分

第十一章 事件处理

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

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

GUI 设计中,程序员需要对组件的某种事件进行响应和处理时,必须完成两个步骤:(1)定义实现某事件监听器接口的事件监听器类,并具体化接口声明中的事件处理抽象方法。(2)为组件注册实现了规定接口的事件监听器对象。

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

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

命令按钮Jbutton主要API:

创建按钮对象:

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

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

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

按钮对象的常用方法:

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

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

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

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

适配器类:frame.addWindowListener(new Terminator());

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

注册事件监听器:

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

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

(3)创建扩展于 WindowAdapter 的监听器类是很好的改进,但还可以进一步将上 面语句也可简化为:frame.addWindowListener(new Terminator());

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

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

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

(2)执行命令所需要的参数。

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

(1)鼠标第一次被按下时调用 mousePressed 方法;

(2)鼠标被释放时调用 mouseReleased 方法;

(3)两个动作完成之后, , 调用 mouseClicked 方法。

AWTEevent 是所有 AWT 事 件 类的父类 , EventObject的直接子类。有些 Swing 组件生成其他类型的事件对象, 一般直接扩展于 EventObject,而不是AWTEvent,位于javax. swing. event.* 。

二.实验部分

1、实验目的与要求

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

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

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

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

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

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

2、实验内容和步骤

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

测试程序1:

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

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

l 用lambda表达式简化程序;

l 掌握JButton组件的基本API;

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

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();//生成ButtonFrame类对象frame
         frame.setTitle("ButtonTest");//设置窗体标题
         frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);//设置关闭按钮
         frame.setVisible(true);//窗口是否可见
      });
   }
}
ButtonTest
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;//JPanel 是一般轻量级容器
   private static final int DEFAULT_WIDTH = 600;//静态常量
   private static final int DEFAULT_HEIGHT = 400;

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

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

点击不同的按钮会变成不同的颜色

简化后的代码:

匿名内部类

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();//生成ButtonFrame类对象frame
         frame.setTitle("ButtonTest");//设置窗体标题
         frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);//设置关闭按钮
         frame.setVisible(true);//窗口是否可见
      });
   }
}
ButtonTest
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;// JPanel 是一般轻量级容器
    private static final int DEFAULT_WIDTH = 600;// 静态常量
    private static final int DEFAULT_HEIGHT = 400;

    public ButtonFrame() {
        setSize(DEFAULT_WIDTH, DEFAULT_HEIGHT);// 设置组件大小
        buttonPanel = new JPanel();
        add(buttonPanel);
        makeButton("yellow", Color.YELLOW);
        makeButton("blue", Color.BLUE);
        makeButton("red", Color.RED);
        makeButton("green", Color.GREEN);
    }

    /**
     * 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); } }
     */
    public void makeButton(String name, Color backgroundColor) {
        JButton button = new JButton(name);
        buttonPanel.add(button);
        button.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent enent) {
                buttonPanel.setBackground(backgroundColor);
            }
        });
    }
}
ButtonFrame

(Lambda表达式)

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();//生成ButtonFrame类对象frame
         frame.setTitle("ButtonTest");//设置窗体标题
         frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);//设置关闭按钮
         frame.setVisible(true);//窗口是否可见
      });
   }
}
ButtonTest
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;// JPanel 是一般轻量级容器
    private static final int DEFAULT_WIDTH = 600;// 静态常量
    private static final int DEFAULT_HEIGHT = 400;

    public ButtonFrame() {
        setSize(DEFAULT_WIDTH, DEFAULT_HEIGHT);// 设置组件大小
        buttonPanel = new JPanel();
        add(buttonPanel);
        makeButton("yellow", Color.YELLOW);
        makeButton("blue", Color.BLUE);
        makeButton("red", Color.RED);
        makeButton("green", Color.GREEN);
    }

    /**
     * An action listener that sets the panel's background color.
     */
    public void makeButton(String name, Color backgroundColor) {
        JButton button = new JButton(name);
        buttonPanel.add(button);
        button.addActionListener((e)-> {
                buttonPanel.setBackground(backgroundColor);
        });
    }
}
ButtonFrame

测试程序2:

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

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

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

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

      // 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();//打印堆栈信息
         }
      });
   }
}
PlafFrame

测试程序3:

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

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

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

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(() -> {
         JFrame frame = new ActionFrame();
         frame.setTitle("ActionTest");
         frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
         frame.setVisible(true);
      });
   }
}
ActionTest
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
      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);

      // 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
      InputMap imap = buttonPanel.getInputMap(JComponent.WHEN_ANCESTOR_OF_FOCUSED_COMPONENT);//InputMap 提供输入事件
      imap.put(KeyStroke.getKeyStroke("ctrl Y"), "panel.yellow");
      imap.put(KeyStroke.getKeyStroke("ctrl B"), "panel.blue");
      imap.put(KeyStroke.getKeyStroke("ctrl R"), "panel.red");

      // associate the names with actions
      ActionMap amap = buttonPanel.getActionMap();//返回用于确定为特定 KeyStroke 绑定触发何种 Action 的 ActionMap
      amap.put("panel.yellow", yellowAction);
      amap.put("panel.blue", blueAction);
      amap.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);//设置与指定键关联的 Value
         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);//设置组件的背景色
      }
   }
}
ActionFrame

测试程序4:

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

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

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

import mouse.MouseFrame;

/**
 * @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);
      });
   }
}
MouseTest
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();//调整窗口大小
   }
}
MouseFrame
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; // 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); }   
   //Dimension 类封装单个对象中组件的宽度和高度
   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();//返回Point2D 的 X 坐标
      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));//setCursor为指定的光标设置光标图像
      }

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

实验2:结对编程练习

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

点名器启动界面

点名器点名界面

import java.util.*;
import java.awt.*;
import javax.swing.*;
import java.awt.event.*;
import java.io.File;
import java.io.FileNotFoundException;

import javax.swing.event.*;
public class NameFrame extends JFrame implements ActionListener{
    private JLabel jla;
    private JLabel jlb;
    private JButton jba;//"push" 按钮的实现
    private static boolean flag = true;//boolean变量
    public NameFrame(){
        this.setLayout(null);//设置 LayoutManager。重写此方法
      //创建三个具有指定文本的 JLabel 实例
        jla = new JLabel("姓名");
        jlb = new JLabel("  ");
        jba = new JButton("开始");
        this.add(jla);//添加组件
        this.add(jlb);
        jla.setFont(new Font("Courier",Font.PLAIN,25));//设置字体
        jla.setHorizontalAlignment(JLabel.CENTER);//设置标签内容沿 X 轴的对齐方式
         jla.setVerticalAlignment(JLabel.CENTER);  //设置标签内容沿 Y 轴的对齐方式      
         jla.setBounds(20,100,180,30);//移动组件并调整其大小
         jlb.setOpaque(true);//如果为 true,则该组件绘制其边界内的所有像素
         jlb.setBackground(Color.cyan);//设置组件的背景色
         jlb.setFont(new Font("Courier",Font.PLAIN,25));
         jlb.setHorizontalAlignment(JLabel.CENTER);
         jlb.setVerticalAlignment(JLabel.CENTER);        
         jlb.setBounds(150,100,150,30);
          
         this.add(jba);
         jba.setBounds(150,150,80,26);
      
         jba.addActionListener(this);//添加监听器按钮

         this.setTitle("点名器");//设置窗体标题
        this.setBounds(400,400,400,300);
        this.setVisible(true);
        this.setDefaultCloseOperation(DISPOSE_ON_CLOSE);
    }
    public void actionPerformed(ActionEvent e){
        int i=0;
        String names[]=new String[47];
        //捕获异常
        try {
            Scanner in=new Scanner(new File("E:\\studentnamelist.txt"));
            while(in.hasNextLine())
            {
                names[i]=in.nextLine();
                i++;
            }
        } catch (FileNotFoundException e1) {
            // TODO Auto-generated catch block
            e1.printStackTrace();
        }
        if(jba.getText()=="开始"){//返回按钮文本
            jlb.setBackground(Color.PINK);
            flag = true;
            new Thread(){   
                public void run(){
                    while(NameFrame.flag){
                    Random r = new Random(); 
                    int i= r.nextInt(47);
                    jlb.setText(names[i]);
                    }
                }
            }.start();//使该线程开始执行;Java 虚拟机调用该线程的 run 方法
            jba.setText("停止");
            jba.setBackground(Color.GREEN);
        }    
        else if(jba.getText()=="停止"){
            flag = false;
            jba.setText("开始");//设置按钮的文本
            jba.setBackground(Color.WHITE);
            jlb.setBackground(Color.WHITE);
        }
     }
    public static void main(String arguments []){ 
        new NameFrame();
    }
}
NameFrame

 

3.实验总结:

在本周的实验中,测试程序环节当中,第一个测试程序花费的时间挺长的,在老师的指导以及助教学长的演示下,第一个实例程序换感觉不错,都基本可以自己独立完成,但是对于将程序改成Lambda表达式还是不太懂。在结对编程环节当中,完全没有任何的思路,想了很久还是不知道从何下手。再看了助教学长的程序之后,还是不太理解。

posted @ 2018-11-25 15:49  薄荷蓝莓  阅读(174)  评论(0编辑  收藏  举报