201871010123-吴丽丽《面向对象程序设计(Java)》第十三周学习总结

                                                                                                 201871010123-吴丽丽《面向对象程序设计(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事件处理基础

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

2、事件监听器(event listener) :事件监听器接收事件源发送的通告(事件对象)后,对发生的事件作出响应。一个事件监听器就是一个实现了专门监听器接口的类实例,该类必须实现接口中的方法,这些方法当事件发生时,被自动执行。
3、事件对象 (event object) : Java将事件的相关信息封装在事件对象中,不同的事件源可以产生不同类别的事件。所有的事件对象都派生于java. util. EventObject类。

 一、AWT事件处理机制的概要:

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

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

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

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

     5、事件源和监听器之间的关系如下图所示:

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

 7、注册监听器方法

eventSourceObject.addEventListener(eventL istenerObject)
以下是注册监听器的一个示例:
ActionListener listener= ...;
JButton button=new JButton(“Ok");

button.addActionListener(istener);

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

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

2)动作事件主要包括:

(a)点击按钮

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

(c)选择菜单项

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

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

2)监听器接口中方法实现
class Mylistener implements ActionListener

{
public void actionPerformed (ActionEvent event)

{ ...... }

}

二、改变观感的方法

Swing程序默认使用Metal观感,采用两种方式改变观感。

第一种:在Java安装的子目录jre/lib下的文件swing. properties中,将属性swing. defaultlaf设置为所希望的观感类名。

swing.defaultlaf=com.sun.java.swing.plaf.motif.MotifLookAndFeel

第二种:调用静态的UIManager. setLookAndFeel方法, 动态地改变观感,提供所想要的观感类名,再调用静态方法Swi ngUtilities. updateComponentTreeUI来刷新全部的组件集。

三、适配器类

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

4、WindowListener接口

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

5、鉴于代码简化的要求,对于不止一个方法的AWT监听器接口都有一个实现了它的所有方法,但却不做任何工作的适配器类。例: WindowAdapter类 。

6、适配器类动态地满足了Java中实现监视器类的技术要求。
7、通过扩展适配器类来实现窗口事件需要的动作

四、注册事件监听器

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

frame.addWindowListener(listener);

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

3、创建扩展于WindowAdapter的监听器类是很好的改进,但还可以进一步将上面语句也可简化为:

frame addWindowListener(new Terminator());

11.2 动作事件

一、动作接口及其类

1、Swing包提供了非常实用的机制来封装动作命令,并将它们连接到多个事件源,这就是Action接口。其中Action扩展于ActionListener借口

2、动作对象是一个封装下列内容的对象:
-命令的说明:一个文本字符串和一个可选图标;

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

3、Action是一个接口,而不是一个类,实现这个接口的类必须要实现它的7个方法。

4、AbstractAction类实现了Action接口中除actionPerformed方法之外的所有方法,这个类存储了所有名/值对,并管理着属性变更监听器。

5、在动作事件处理应用中,可以直接扩展AbstractAction类,并在扩展类中实现actionPerformed方法。

二、击键关联映射

1、将一个动作对象添加到击键中,以便让用户敲击键盘命令来执行这个动作。
2、将动作与击键关联起来,需生成KeyStroke类对象。

KeyStroke ctrBKey = KeyStroke.getKeyStroke("CtrlB");

3、下面是将击键与动作对象关联起来的方式(桥梁:动作键对象描述字符串)
InputMap imap =buttonPanel.getInputMap(JComponent.WHEN_ ANCESTOR_ OF_FOCUSED_COMPONENT);
imap.put(KeyStroke.getKeyStrokel("ctrl Y"), " panel.yellow");

ActionMap amap = buttonPanel.getActionMap();

amap.put(" panel,yellow", yellowAction);

11.3鼠标事件
1、鼠标事件
-MouseEvent

2、鼠标监听器接口
-MouseListener
-MouseMotionListener

3、鼠标监听器适配器
-MouseAdapter
-MouseMotionAdapter

4、用户点击鼠标按钮时,会调用三个监听器方法:
-鼠标第一次被按下时调用mousePressed方法;

-鼠标被释放时调用mouseReleased方法;
-两个动作完成之后,调用mouseClicked方法。

5、鼠标在组件上移动时,会调用mouseMoved方法。
6、如果鼠标在移动的时候还按下了鼠标,则会调用mouseDragged方法。

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

8、MouseEvent类中的重要方法

- public int getX( );

- public int getY( );
- public Point getPoint( );
-public int getClickCount( );

9、设置光标
-java.awt.Component;
public void setCursor(Cursor C);
-java.awt.Cursor;
public static Cursor getDefaultCursor( );
public static Cursor getPredefinedCursor(int type);

11.4 AWT事件继承层次

1、所有的事件都是由java.util包中的EventObject类扩展而来。
2、AWTEevent是所有AWT事件类的父类,也是EventObject的直接子类。
3、有些Swing组件生成其他类型的事件对象,一般直“接扩展于EventObject,而不是AWTEvent,位于javax. swing. event. *。
4、事件对象封装了事件源与监听器彼此通信的事件信息。在必要的时候,可以对传递给监听器对象的事件对象进行分析。

5、AWT事件类的继承关系图如下:

 11.4.1AWT中的事件分类

 1、AWT将事件分为低级(low-level)事件和语义(semantic)事件。
-语义事件:表达用户动作的事件。

例:点击按钮(Act ionEvent)。

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

(1)语义事件

AWT事件中常用的语义事件:
a)ActionEvent (对应按钮点击、菜单选择、选择列表项或在文本域中键入ENTER);
b)AdjustmentEvent (用户调节滚动条);
c)ItemEvent (用户从复选框或列表项中选择-项)。

(2)低层事件
AWT事件中常用的5个低级事件类:

a)KeyEvent(一个键被按下或释放) ;
b)MouseEvent (鼠标被按下、释放、移动或拖动);
c)MouseWheelEvent (鼠标滚轮被转动) ;
d)FocusEvent (某个组件获得或失去焦点);

e)WindowEvent (窗口状态改变)。

第二部分:实验部分

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

实验时间 2019-11-22

1、实验目的与要求

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

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

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

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

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

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

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

测试程序1:

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

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

3) lambda表达式简化程序;

4)掌握JButton组件的基本API;

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

ButtonFrame.java文件中代码如下:

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
      var yellowButton = new JButton("Yellow");    //创建按钮对象
      var blueButton = new JButton("Blue");
      var redButton = new JButton("Red");

      buttonPanel = new JPanel();

      // add buttons to panel
      buttonPanel.add(yellowButton);  //通过调用add方法将按钮添加到面板中
      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);

      // 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  //ColorAction类实现ActionListener接口
   {
      private Color backgroundColor;

      public ColorAction(Color c)
      {
         backgroundColor = c;
      }

      public void actionPerformed(ActionEvent event) //actionPerformed()方法用来接收ActionEvent对象参数
      {
         buttonPanel.setBackground(backgroundColor);  //设置背景
      }
   }
}
View Code

ButtonTest.java文件中代码如下:

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);  //设置框架为可见性
      });
   }
}
View Code

运行结果如下所示:

 任意点其中的按钮,其背景颜色将被换成该按钮上写的颜色

 用lambda表达式修改ButtonFrame.java里的程序后,代码如下:

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

      // create buttons
      //连续调用三次makeButton方法
      makeButton("yellow",Color.YELLOW);
      makeButton("blue",Color.BLUE);
      makeButton("red",Color.RED);
      //将面板添加至框架中
      add(buttonPanel);

   }
   //在这里定义了一个makeButton方法,没有显示的定义一个类,每次调用这个方法时,它会建立实现ActionListener接口的一个类的实例
   public void makeButton(String name,Color backgroundColor)
   {
       JButton button=new JButton(name);
       buttonPanel.add(button);
       button.addActionListener(event->
           buttonPanel.setBackground(backgroundColor));  //使用lambda表达式
   }
}
View Code

测试程序2

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

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

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

PlafFrame.java代码如下:

package plaf;

import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.UIManager;
import javax.swing.SwingUtilities;


public class PlafFrame extends JFrame
 {    
    private JPanel buttonPanel;
    public PlafFrame() 
    {
        buttonPanel = new JPanel();
        UIManager.LookAndFeelInfo[] infos=UIManager.getInstalledLookAndFeels(); //为了列举安装的所有观感实现,调用getInstalledLookAndFeels()方法
        for(UIManager.LookAndFeelInfo info:infos)  //for each循环,进而得到每一种观感的名字和类名
            makeButton(info.getName(),info.getClassName());
        add(buttonPanel);  
        pack();  //pack()方法用来调整窗口的大小
    }
    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);   //调用静态的UIManager.setLookAndFeel()方法,并提供所想要的观感类名
                SwingUtilities.updateComponentTreeUI(this);//调用静态的SwingUtilities.updateComponentTreeUI方法来刷新组件集
                pack();
            }
            catch (Exception e)  //捕获异常
            {
                e.printStackTrace();
            }
        });
        
    }

}
View Code

PlafTest.java代码如下:

package plaf;

import java.awt.EventQueue;

import javax.swing.JFrame;

public class PlafTest {
     public static void main(String[] args) 
{     //使用了匿名类
    EventQueue.invokeLater(() -> {
        var frame = new PlafFrame();   //创建一个新对象
        frame.setTitle("ButtonTest");    //设置框架标题
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        frame.setVisible(true);   //设置框架为可见
    });
 }
}
View Code

运行结果如下:

 点不一样的按钮会出现不一样的结果,如摁了CDE/Motif按钮会出现以下结果:

测试程序3

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

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

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

 ActionFrame.java代码如下:

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);    //创建colorAction类的对象
      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));  //通过调用add方法将按钮添加到面板中
      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 inputMap = buttonPanel.getInputMap(JComponent.WHEN_ANCESTOR_OF_FOCUSED_COMPONENT);//使用getInputMap方法从组件中得到输入映射
      //三个输入映射
      inputMap.put(KeyStroke.getKeyStroke("ctrl Y"), "panel.yellow");  //调用KeyStroke类中的getKeyStroke方法
      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();  //调用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)
      {
         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");   //返回被存储的名/值对的值,并将其进行强制类型转换为Color
         buttonPanel.setBackground(color);    //设置背景颜色
      }
   }
}
View Code

ActionTest.java代码如下:

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

运行结果如下:

 当我按Ctrl+Y键时,出现以下结果:

测试程序4

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

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

 MouseFrame.java代码如下:

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();    //pack方法是用来确定框架的最佳大小
   }
}
View Code

MouseTest.java代码如下:

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);     //设置框架为可见
      });
   }
}
View Code

MouseComponent.java代码如下:

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)   //mousePressed方法,当鼠标点击所在小方块的像素之外时,就会绘制一个新的小方块
      {
         // 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)   //mouseclick方法,双击鼠标时,将小方块擦除
      {
         // 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();   //返回事件相对于源组件的水平x坐标
            int y = event.getY();   //返回事件相对于源组件的垂直y坐标

            // drag the current rectangle to center it at (x, y)
            current.setFrame(x - SIDELENGTH / 2, y - SIDELENGTH / 2, SIDELENGTH, SIDELENGTH);  //将此Rectangle2D外部边界的位置和大小设置为矩形值
            repaint();   //repaint方法用来重绘组件
         }
      }
   }   
}
View Code

运行结果如下:

 当在框架上点击后出现以下结果:

实验2:结对编程练习

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

 

1 点名器启动界面

 

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

                                      图点名器点名界面

 结对编程实验思路如下:

和结对同伴梁丽珍一起讨论的照片如下:

实验代码如下:

package checkroll;

import java.awt.Color;
import java.awt.Font;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.File;
import java.io.FileNotFoundException;
import java.util.Random;
import java.util.Scanner;

import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;

public class NameFrame extends JFrame implements ActionListener {
    private JLabel jla;
    private JLabel jlb;
    private JButton jba;    //push按钮的实现
    private static boolean flag = true;    //开始的按钮是否点过
    public NameFrame() {
        this.setLayout(null);
        //条件按钮
            jla = new JLabel("姓名");
            jlb = new JLabel("准备");
            jba = new JButton("开始");
            this.add(jla);//添加组件
            this.add(jlb);
            jla.setFont(new Font("Courier",Font.PLAIN,22));//设置字体
            jla.setHorizontalAlignment(JLabel.CENTER);//x轴对称
             jla.setVerticalAlignment(JLabel.CENTER);  //y轴对称      
             jla.setBounds(20,100,180,30);
             jlb.setOpaque(true);//设置控件不透明
             jlb.setBackground(Color.blue);//设置背景颜色
             jlb.setFont(new Font("Courier",Font.PLAIN,22));
            jlb.setHorizontalAlignment(JLabel.CENTER);
             jlb.setVerticalAlignment(JLabel.CENTER);        
             jlb.setBounds(150,100,120,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[50];
            try {
                Scanner in=new Scanner(new File("D:\计师1班.txt"));
                while(in.hasNextLine())//hasNextLine()用来检测下一行有没有输入
                {
                    names[i]=in.nextLine();//因为之前用hasNextLine(),所以这里需要用nextLine()
                    i++;
                }
            } catch (FileNotFoundException e1) {
                // TODO Auto-generated catch block
                e1.printStackTrace();
            }
            if(jba.getText()=="开始"){//返回按钮
                jlb.setBackground(Color.MAGENTA);
                flag = true;
              //用new Thread()进行异步加载
                new Thread(){   
                    public void run(){
                        while(NameFrame.flag){
                        Random r = new Random(); 
                        int i= r.nextInt(35);//返还该元素,并重新选择另一个元素
                        jlb.setText(names[i]);
                        }
                    }
                }.start();//使该线程开始执行;Java 虚拟机调用该线程的 run 方法
                jba.setText("停止");
                jba.setBackground(Color.YELLOW);
            }    
            else if(jba.getText()=="停止"){
                flag = false;
                jba.setText("开始");//按钮标题
                jba.setBackground(Color.WHITE);//“开始”颜色
                jlb.setBackground(Color.blue);
            }
         }
        public static void main(String arguments []){ 
            new NameFrame();
        }
    
}
View Code

实验运行结果如下:

 实验总结:

通过本周的学习,我掌握了事件处理的基本原理,理解了其用途;并了解学习了以下几点:1.AWT事件模型的工作机制;2.事件处理的基本编程模型;3.了解了GUI界面组件观感设置方法;4.WindowAdapter类、AbstractAction类的用法;5.GUI程序中鼠标事件处理技术。在本次实验的结对编程中,用到了异步加载,这知识点老师在上课时没涉及到,我和同伴通过在网上查询了解了这方面的一些知识,不过在编程实验中还是遇到了一些疑惑,但之后通过向同学们请教,了解了自己的问题所在,最后学会了如何设计一个小型界面,受益颇多!

原文地址:https://www.cnblogs.com/lily-2018/p/11913857.html