201871010111-刘佳华《面向对象程序设计(java)》第十三周学习总结

201871010111-刘佳华《面向对象程序设计(java)》第十三周学习总结

实验十一 图形界面事件处理技术

实验时间 2019-11-22

第一部分:理论知识总结

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

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

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

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

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

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

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

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

 

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

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

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

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

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

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

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

(1)点击按钮

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

(3)选择菜单项

(4)在文本框中输入回车

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)按钮对象的常用方法:

① getLabel( ):返回按钮的标签字符串;
② setLabel(String s):设置按钮的标签为字符串s。

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

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

10.适配器类

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

WindowListener listener=…..;
frame.addWindowListener(listener);
⚫ 窗口监听器必须是实现WindowListener接口的
类的一个对象,WindowListener接口中有七个
方法,它们的名字是自解释的。

11.鉴于代码简化的要求,对于有不止一个方法的AWT监听器接口都有一个实现了它的所有方法,但却

不做任何工作的适配器类。
例:WindowAdapter类。

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

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

12.注册事件监听器

可将一个Terminator对象注册为事件监听器:
WindowListener listener=new Terminator();
frame.addWindowListener(listener);
⚫ 只要框架产生一个窗口事件,该事件就会传递给
监听器对象。

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

13.动作事件

(1)激活一个命令可以有多种方式,如用户可以通过
菜单、击键或工具栏上的按钮选择特定的功能。
(2)在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) 掌握事件处理的基本原理,理解其用途;

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

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

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

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

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

2、实验内容和步骤

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

测试程序1:

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

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

lambda表达式简化程序;

掌握JButton组件的基本API;

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

源代码:

 1 package Damo;
 2 
 3 import java.awt.*;
 4 import javax.swing.*;
 5 
 6 /**
 7  * @version 1.35 2018-04-10
 8  * @author Cay Horstmann
 9  */
10 public class ButtonTest
11 {
12    public static void main(String[] args)
13    {
14       EventQueue.invokeLater(() -> {
15          var frame = new ButtonFrame();
16          frame.setTitle("ButtonTest");
17          frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
18          frame.setVisible(true);
19       });
20    }
21 }
ButtonTest
 1 package Damo;
 2 
 3 import java.awt.*;
 4 import java.awt.event.*;
 5 import javax.swing.*;
 6 
 7 /**
 8  * A frame with a button panel.
 9  */
10 public class ButtonFrame extends JFrame
11 {
12    private JPanel buttonPanel;
13    private static final int DEFAULT_WIDTH = 300;
14    private static final int DEFAULT_HEIGHT = 200;
15 
16    public ButtonFrame()
17    {      
18       setSize(DEFAULT_WIDTH, DEFAULT_HEIGHT);//设定大小
19 
20       // create buttons
21       var yellowButton = new JButton("Yellow");//设置组件
22       var blueButton = new JButton("Blue");
23       var redButton = new JButton("Red");
24 
25       buttonPanel = new JPanel();//面板
26 
27       // add buttons to panel
28       buttonPanel.add(yellowButton);//组件添加至面板之中
29       buttonPanel.add(blueButton);
30       buttonPanel.add(redButton);
31 
32       // add panel to frame
33       add(buttonPanel);//再将面板添加至frame中
34 
35       // create button actions
36       var yellowAction = new ColorAction(Color.YELLOW);//设置事件监听器
37       var blueAction = new ColorAction(Color.BLUE);
38       var redAction = new ColorAction(Color.RED);
39 
40       // associate actions with buttons
41       yellowButton.addActionListener(yellowAction);//注册  .addActionListener(对象)
42       blueButton.addActionListener(blueAction);
43       redButton.addActionListener(redAction);
44    }
45 
46    /**
47     * An action listener that sets the panel's background color.
48     */
49    private class ColorAction implements ActionListener
50    {
51       private Color backgroundColor;
52 
53       public ColorAction(Color c)
54       {
55          backgroundColor = c;
56       }
57 
58       public void actionPerformed(ActionEvent event)//响应事件改变背景颜色
59       {
60          buttonPanel.setBackground(backgroundColor);
61       }
62    }
63 }
ButtonFrame

运行截图:

       

通过lambda表达式简化后的代码:

 1 package button;
 2 
 3 import java.awt.*;
 4 import java.awt.event.*;
 5 import javax.swing.*;
 6 
 7 /**
 8  * A frame with a button panel.
 9  */
10 public class ButtonFrame extends JFrame
11 {
12    private JPanel buttonPanel;
13    private static final int DEFAULT_WIDTH = 300;
14    private static final int DEFAULT_HEIGHT = 200;
15 
16    public ButtonFrame()
17    {    
18       setSize(DEFAULT_WIDTH, DEFAULT_HEIGHT);
19            buttonPanel = new JPanel();
20       
21       makeButton("yellow",Color.YELLOW);
22       makeButton("blue",Color.BLUE);
23       makeButton("red",Color.RED);
24             add(buttonPanel);
25 
26    }
27    
28     public void makeButton(String name,Color backgroundColor)//将所有的创建组件,注册类容全部放置在makebutton方法中,只需要方法调用即可
29    {
30        JButton button=new JButton(name);
31        buttonPanel.add(button);
32        button.addActionListener(event->
33            buttonPanel.setBackground(backgroundColor));//event - button.ButtonFrame.makeButton(...).() -> {...} ActionListener.actionPerformed(ActionEvent)
34    }
35 }
ButtonFrame

运行结果与源程序一致。

测试程序2:

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

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

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

代码如下:

 1 package Damo;
 2 
 3 import java.awt.*;
 4 import javax.swing.*;
 5 
 6 /**
 7  * @version 1.32 2015-06-12
 8  * @author Cay Horstmann
 9  */
10 public class PlafTest
11 {
12    public static void main(String[] args)
13    {
14       EventQueue.invokeLater(() -> {
15          JFrame frame = new PlafFrame();
16          frame.setTitle("PlafTest");
17          frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
18          frame.setVisible(true);
19       });
20    }
21 }
PlafTest
 1 package Damo;
 2 
 3 import javax.swing.JButton;
 4 import javax.swing.JFrame;
 5 import javax.swing.JPanel;
 6 import javax.swing.SwingUtilities;
 7 import javax.swing.UIManager;
 8 
 9 /**
10  * A frame with a button panel for changing look-and-feel
11  */
12 public class PlafFrame extends JFrame
13 {
14    private JPanel buttonPanel;
15 
16    public PlafFrame()
17    {
18       buttonPanel = new JPanel();
19       //UIManager管理组件观感
20       UIManager.LookAndFeelInfo[] infos = UIManager.getInstalledLookAndFeels();
21       for (UIManager.LookAndFeelInfo info : infos)
22          makeButton(info.getName(), info.getClassName());
23 
24       add(buttonPanel);
25       pack();
26    }
27 
28    /**
29     * Makes a button to change the pluggable look-and-feel.
30     * @param name the button name
31     * @param className the name of the look-and-feel class
32     */
33    private void makeButton(String name, String className)
34    {
35       // 添加按钮至Panel
36 
37       JButton button = new JButton(name);
38       buttonPanel.add(button);
39 
40       // 建立按钮操作
41 
42       button.addActionListener(event -> {
43          // 按钮操作: 选择一个新的外观
44          try
45          {
46             UIManager.setLookAndFeel(className);
47             SwingUtilities.updateComponentTreeUI(this);
48             pack();//根据窗口里面的布局及组件的preferredSize来确定frame的最佳大小。
49          }
50          catch (Exception e)
51          {
52             e.printStackTrace();
53          }
54       });
55    }
56 }
PlafFrame

运行截图:

 

 

 

测试程序3:

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

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

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

 1 package Damo;
 2 
 3 import java.awt.*;
 4 import javax.swing.*;
 5 
 6 /**
 7  * @version 1.34 2015-06-12
 8  * @author Cay Horstmann
 9  */
10 public class ActionTest
11 {
12    public static void main(String[] args)
13    {
14       EventQueue.invokeLater(() -> {
15          var frame = new ActionFrame();
16          frame.setTitle("ActionTest");
17          frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
18          frame.setVisible(true);
19       });
20    }
21 }
ActionTest
 1 package Damo;
 2 
 3 import java.awt.*;
 4 import java.awt.event.*;
 5 import javax.swing.*;
 6 
 7 /**
 8  * A frame with a panel that demonstrates color change actions.
 9  */
10 public class ActionFrame extends JFrame
11 {
12    private JPanel buttonPanel;
13    private static final int DEFAULT_WIDTH = 300;
14    private static final int DEFAULT_HEIGHT = 200;
15 
16    public ActionFrame()
17    {
18       setSize(DEFAULT_WIDTH, DEFAULT_HEIGHT);
19 
20       buttonPanel = new JPanel();
21 
22       // 定义操作
23       var yellowAction = new ColorAction("Yellow", new ImageIcon("C:\\Users\\83583\\Desktop\\java\\corejava\\v1ch11\\yellow-ball.gif"),
24             Color.YELLOW);
25       var blueAction = new ColorAction("Blue", new ImageIcon("C:\\Users\\83583\\Desktop\\java\\corejava\\v1ch11\\blue-ball.gif"), Color.BLUE);
26       var redAction = new ColorAction("Red", new ImageIcon("C:\\Users\\83583\\Desktop\\java\\corejava\\v1ch11\\red-ball.gif"), Color.RED);
27 
28       // 为这些操作添加按钮
29       buttonPanel.add(new JButton(yellowAction));//注册
30       buttonPanel.add(new JButton(blueAction));
31       buttonPanel.add(new JButton(redAction));
32 
33       // 将 panel 添加置 frame
34       add(buttonPanel);
35 
36       // 将Y、B和R键与名称关联
37       InputMap inputMap = buttonPanel.getInputMap(JComponent.WHEN_ANCESTOR_OF_FOCUSED_COMPONENT);
38       inputMap.put(KeyStroke.getKeyStroke("ctrl Y"), "panel.yellow");
39       inputMap.put(KeyStroke.getKeyStroke("ctrl B"), "panel.blue");
40       inputMap.put(KeyStroke.getKeyStroke("ctrl R"), "panel.red");
41 
42       // 将名称与操作关联
43       ActionMap actionMap = buttonPanel.getActionMap();
44       actionMap.put("panel.yellow", yellowAction);
45       actionMap.put("panel.blue", blueAction);
46       actionMap.put("panel.red", redAction);
47    }
48    
49    public class ColorAction extends AbstractAction
50    {
51       /**
52        * Constructs a color action.
53        * @param name the name to show on the button
54        * @param icon the icon to display on the button
55        * @param c the background color
56        */
57       public ColorAction(String name, Icon icon, Color c)
58       {
59          putValue(Action.NAME, name);
60          putValue(Action.SMALL_ICON, icon);
61          putValue(Action.SHORT_DESCRIPTION, "Set panel color to " + name.toLowerCase());
62          putValue("color", c);
63       }
64 
65       public void actionPerformed(ActionEvent event)
66       {
67          var color = (Color) getValue("color");
68          buttonPanel.setBackground(color);
69       }
70    }
71 }
ActionFrame

  

 

 将键盘事件与鼠标时间一起连接到了该按钮上,在鼠标单击该按钮时,会改变panel的颜色,在按住Ctrl+y,r,b时也会改变panel的颜色。

测试程序4:

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

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

 1 package Damo;
 2 
 3 import java.awt.*;
 4 import javax.swing.*;
 5 
 6 /**
 7  * @version 1.35 2018-04-10
 8  * @author Cay Horstmann
 9  */
10 public class MouseTest
11 {
12    public static void main(String[] args)
13    {
14       EventQueue.invokeLater(() -> {
15          var frame = new MouseFrame();
16          frame.setTitle("MouseTest");
17          frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
18          frame.setVisible(true);
19       });
20    }
21 }
MouseTest
 1 package Damo;
 2 
 3 import javax.swing.*;
 4 
 5 /**
 6  * A frame containing a panel for testing mouse operations
 7  */
 8 public class MouseFrame extends JFrame
 9 {
10    public MouseFrame()
11    {
12       add(new MouseComponent());
13       pack();
14    }
15 }
MouseFrame
  1 package Damo;
  2 
  3 import java.awt.*;
  4 import java.awt.event.*;
  5 import java.awt.geom.*;
  6 import java.util.*;
  7 import javax.swing.*;
  8 
  9 /**
 10  * A component with mouse operations for adding and removing squares.
 11  */
 12 public class MouseComponent extends JComponent
 13 {
 14    private static final int DEFAULT_WIDTH = 300;
 15    private static final int DEFAULT_HEIGHT = 200;
 16 
 17    private static final int SIDELENGTH = 10;
 18    private ArrayList<Rectangle2D> squares;
 19    private Rectangle2D current; // 包含鼠标光标的正方形
 20 
 21    public MouseComponent()
 22    {
 23       squares = new ArrayList<>();
 24       current = null;
 25 
 26       addMouseListener(new MouseHandler());
 27       addMouseMotionListener(new MouseMotionHandler());
 28    }
 29 
 30    public Dimension getPreferredSize() 
 31    {
 32       return new Dimension(DEFAULT_WIDTH, DEFAULT_HEIGHT);
 33    }   
 34    
 35    public void paintComponent(Graphics g)
 36    {
 37       var g2 = (Graphics2D) g;
 38 
 39       // 绘制所有正方形
 40       for (Rectangle2D r : squares)
 41          g2.draw(r);
 42    }
 43 
 44    /**
 45     * Finds the first square containing a point.
 46     * @param p a point
 47     * @return the first square that contains p
 48     */
 49    public Rectangle2D find(Point2D p)
 50    {
 51       for (Rectangle2D r : squares)
 52       {
 53          if (r.contains(p)) return r;
 54       }
 55       return null;
 56    }
 57 
 58    /**
 59     * Adds a square to the collection.
 60     * @param p the center of the square
 61     */
 62    public void add(Point2D p)
 63    {
 64       double x = p.getX();
 65       double y = p.getY();
 66 
 67       current = new Rectangle2D.Double(x - SIDELENGTH / 2, y - SIDELENGTH / 2,
 68          SIDELENGTH, SIDELENGTH);
 69       squares.add(current);
 70       repaint();
 71    }
 72 
 73    /**
 74     * Removes a square from the collection.
 75     * @param s the square to remove
 76     */
 77    public void remove(Rectangle2D s)
 78    {
 79       if (s == null) return;
 80       if (s == current) current = null;
 81       squares.remove(s);
 82       repaint();
 83    }
 84 
 85    private class MouseHandler extends MouseAdapter
 86    {
 87       public void mousePressed(MouseEvent event)
 88       {
 89          // 如果光标不在正方形内,则添加新的正方形
 90          current = find(event.getPoint());
 91          if (current == null) add(event.getPoint());
 92       }
 93 
 94       public void mouseClicked(MouseEvent event)
 95       {
 96          // 如果双击,则删除当前正方形
 97          current = find(event.getPoint());
 98          if (current != null && event.getClickCount() >= 2) remove(current);
 99       }
100    }
101 
102    private class MouseMotionHandler implements MouseMotionListener
103    {
104       public void mouseMoved(MouseEvent event)
105       {
106          // 如果鼠标光标位于矩形内,请将其设置为十字光标
107 
108          if (find(event.getPoint()) == null) setCursor(Cursor.getDefaultCursor());
109          else setCursor(Cursor.getPredefinedCursor(Cursor.CROSSHAIR_CURSOR));
110       }
111 
112       public void mouseDragged(MouseEvent event)
113       {
114          if (current != null)
115          {
116             int x = event.getX();
117             int y = event.getY();
118 
119             // 拖动当前矩形使其居中(x,y)
120             current.setFrame(x - SIDELENGTH / 2, y - SIDELENGTH / 2, SIDELENGTH, SIDELENGTH);
121             repaint();
122          }
123       }
124    }   
125 }
MouseComponent

运行结果:

实验2:结对编程练习

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

 

1 点名器启动界面

2 点名器随机显示姓名界面

 图3 点名器点名界面

 1)结对编程整体思路:

  我们先设计了一个GUI图形界面,然后将学生信息读取后存储带一个数组当中,在实现监听器类actionPerformed方法时,采用随机数下标获取学生信息数组中的值,再重写timer类的schedule类中的run方法实现定时器功能。当button中的内容为“开始”时,启动定时器,当button中的内容为“停止”时,则调用timer类对象的cancel方法停用定时器,这样就完成了对点名器的代码编程。

结对编程整体代码:

  1 package Pearwork2;
  2 
  3 import java.awt.Color;
  4 import java.awt.event.*;
  5 import java.awt.EventQueue;
  6 import java.awt.Font;
  7 import java.awt.GridLayout;
  8 import java.awt.Panel;
  9 import java.awt.TextField;
 10 import java.io.File;
 11 import java.util.Scanner;
 12 import java.util.Timer;
 13 import java.util.TimerTask;
 14 import java.io.BufferedReader;
 15 import java.io.FileInputStream;
 16 import java.io.FileNotFoundException;
 17 import java.io.IOException;
 18 import java.io.InputStreamReader;
 19 
 20 import javax.swing.JButton;
 21 import javax.swing.JFrame;
 22 
 23 public class Teamwork01 {
 24     public static void main(String[] args) {
 25 
 26         String[] name = new String[35];
 27         Scanner scanner = new Scanner(System.in);
 28         File file = new File("C:\\Users\\83583\\Desktop\\2019studentlist.txt");
 29         try {
 30             FileInputStream F = new FileInputStream(file);
 31             BufferedReader in = new BufferedReader(new InputStreamReader(F));
 32             String temp = null;
 33             int i = 0;
 34             while ((temp = in.readLine()) != null) {
 35                 name[i] = temp;
 36                 i++;
 37             }
 38         } catch (FileNotFoundException e) {
 39             System.out.println("文件未找到!! ");
 40             e.printStackTrace();
 41         } catch (IOException e) {
 42             e.printStackTrace();
 43         }
 44 
 45         EventQueue.invokeLater(() -> {
 46             JFrame frame = new nameFrame(name);
 47             frame.setTitle("随机点名器 ");
 48             // frame.setBackground(Color.green);
 49             frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
 50             frame.setVisible(true);
 51         });
 52     }
 53 }
 54 
 55 class nameFrame extends JFrame {
 56     private JButton button;
 57     private TextField text;
 58     private Panel panel1;
 59     private Panel panel2;
 60     private String[] name;
 61 
 62     public nameFrame(String[] name) {
 63         this.name = name;
 64         this.setSize(500, 400);
 65         this.setLayout(null);
 66         button = new JButton("开始");
 67         button.setFont(new Font("楷体", Font.PLAIN, 25));
 68 
 69         button.setBackground(Color.red);
 70         text = new TextField("随机点名器");
 71         text.setFont(new java.awt.Font("随机点名器", 1, 22));
 72         panel1 = new Panel();
 73         panel1.setLayout(new GridLayout(1, 1));
 74         panel1.setBounds(180, 120, 150, 50);
 75         panel1.add(text);
 76         panel2 = new Panel();
 77         panel2.setLayout(new GridLayout(1, 1));
 78         panel2.setBounds(180, 200, 150, 50);
 79         panel2.add(button);
 80         this.add(panel1);
 81         this.add(panel2);
 82 
 83         buttonAction ba = new buttonAction();
 84         randNameAction ra = new randNameAction();
 85         button.addActionListener(ba);
 86         button.addActionListener(ra);
 87     }
 88 
 89     public class buttonAction implements ActionListener {
 90         public void actionPerformed(ActionEvent event) {
 91             if (button.getText() == "开始") {
 92                 button.setText("结束");
 93                 text.setBackground(Color.red);
 94                 button.setBackground(Color.yellow);
 95             } else {
 96                 button.setText("开始");
 97                 text.setBackground(null);
 98                 button.setBackground(Color.red);
 99             }
100         }
101     }
102 
103     public class randNameAction implements ActionListener {
104         private Timer time;
105 
106         public void actionPerformed(ActionEvent event) {
107             if (button.getText() == "开始") {
108                 time = new Timer();
109                 time.schedule(new TimerTask() {
110                     public void run() {
111                         int a = (int) (Math.random() * name.length);
112                         text.setText(name[a]);
113                     }
114                 }, 0, 50);
115             } else {
116                 time.cancel();
117             }
118         }
119     }
120 }
Teamwork01

 2)运行截图:

   

3) 结对编程讨论图片:

 三、实验总结:

     通过本周学习,我基本掌握了事件处理的基本原理及AWT事件模型的工作机制;掌握事件处理的基本编程模型;并用多种方法简化代码,在老师和同伴的教导进一步理解了匿名内部类,但对于 GUI界面组件观感设置方法还不太理解; 掌握了AbstractAction类的用法及GUI程序中鼠标事件处理技术。此外,在本次结对编程中也遇到了一些问题,比如说在终止timer时,不知道如何终止timer.在查阅了一些资料后了解到了cancel方法停用定时器,达到结束产生随机数组下标的目的;相信会对以后的学习会产生帮助。

猜你喜欢

转载自www.cnblogs.com/JerryLau-213/p/11921557.html
今日推荐