理论知识:事件处理

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

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

实验时间 2018-11-22

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();frame.setTitle("ButtonTest");//设置窗口的标题
         frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);frame.setVisible(true);//将窗口设为可见的
      });}
}

button

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);//通过setsize来更改框架的宽度和高度// create buttonsJButton yellowButton = new JButton("Yellow");JButton blueButton = new JButton("Blue");JButton redButton = new JButton("Red");//生成三个按钮对象,string影响的是显示在button上的文本
buttonPanel = new JPanel();// add buttons to panel
      buttonPanel.add(yellowButton);buttonPanel.add(blueButton);buttonPanel.add(redButton);//向内容窗格添加三个容器组件// add panel to frame
      add(buttonPanel);// create button actionsColorAction yellowAction = new ColorAction(Color.YELLOW);ColorAction blueAction = new ColorAction(Color.BLUE);ColorAction redAction = new ColorAction(Color.RED);//生成三个ColorAction(监听器类)对象// 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 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);// 通过setsize来更改框架的宽度和高度
buttonPanel = new JPanel();add(buttonPanel);makeButton("yellow", Color.yellow);makeButton("blue", Color.blue);makeButton("red", Color.red);makeButton("green", Color.green);//添加一个新的组件只需要该条语句
    }public void makeButton(String name, Color backgroundColor) {JButton button = new JButton(name);buttonPanel.add(button);ColorAction action = new ColorAction(backgroundColor);button.addActionListener(action);}/*** 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 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);// 通过setsize来更改框架的宽度和高度
buttonPanel = new JPanel();add(buttonPanel);makeButton("yellow", Color.yellow);makeButton("blue", Color.blue);makeButton("red", Color.red);makeButton("green", Color.green);// 添加一个新的组件只需要该条语句
    }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() {// 不能直接使用接口,new后面有一个匿名的类名,后面的ActionListener通过匿名类调用
            @Overridepublic void actionPerformed(ActionEvent e) {// TODO Auto-generated method stub
                buttonPanel.setBackground(backgroundColor);}});}}

buttonFrame

通过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);// 通过setsize来更改框架的宽度和高度
buttonPanel = new JPanel();add(buttonPanel);makeButton("yellow", Color.yellow);makeButton("blue", Color.blue);makeButton("red", Color.red);makeButton("green", Color.green);// 添加一个新的组件只需要该条语句
    }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);});}
}

plaf

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();//UIManager 管理当前外观、可用外观集合及获取各种默认值的便捷方法。//返回表示当前可用的 LookAndFeel 实现的 LookAndFeelInfo 数组。应用程序可以使用 LookAndFeelInfo 对象为用户构造外观选项的菜单,或确定在启动时要设置哪个外观 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-feeltry{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);});}
}

action

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 actionsAction yellowAction = new ColorAction("Yellow", new ImageIcon("yellow-ball.gif"),//Action 接口提供 ActionListener 接口的一个有用扩展,以便若干控件访问相同的功能Color.YELLOW);//可以将此接口添加到现有类中,或者用它创建一个适配器(通常通过子类化 AbstractAction 来实现)。Action blueAction = new ColorAction("Blue", new ImageIcon("blue-ball.gif"), Color.BLUE);Action redAction = new ColorAction("Red", new ImageIcon("red-ball.gif"), Color.RED);
//根据指定的文件创建一个 ImageIcon。使用 MediaTracker 预载图像以监视图像的加载状态。指定 String 可以是一个文件名或是一条文件路径。// add buttons for these actionsbuttonPanel.add(new JButton(yellowAction));buttonPanel.add(new JButton(blueAction));buttonPanel.add(new JButton(redAction));// add panel to frameadd(buttonPanel);//添加组件// associate the Y, B, and R keys with namesInputMap imap = buttonPanel.getInputMap(JComponent.WHEN_ANCESTOR_OF_FOCUSED_COMPONENT);//使用继承自 JComponent 的组件//当接收组件是获得焦点的组件的祖先或者其本身就是获得焦点的组件时,应该调用命令。 imap.put(KeyStroke.getKeyStroke("ctrl Y"), "panel.yellow");imap.put(KeyStroke.getKeyStroke("ctrl B"), "panel.blue");imap.put(KeyStroke.getKeyStroke("ctrl R"), "panel.red");//InputMap 提供输入事件(目前只使用 KeyStroke)和 Object 之间的绑定。InputMap 通常与 ActionMap 一起使用,//以确定按下键时执行一个 Action。InputMap 可以有一个父级,可搜索它来获得 InputMap 中未定义的绑定。// associate the names with actionsActionMap amap = buttonPanel.getActionMap();amap.put("panel.yellow", yellowAction);amap.put("panel.blue", blueAction);amap.put("panel.red", redAction);//ActionMap 提供从 Object(称为键 或 Action 名)到 Action 的映射。当按下某一个键时,ActionMap 通常与 InputMap 一起使用来定位特定操作。//与 InputMap 一同使用时,ActionMap 可以有一个父级,用来搜索没有在该 ActionMap 中定义的键。
      }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设置与指定键关联的值putValue(Action.NAME, name);//用于菜单或按钮的名字putValue(Action.SMALL_ICON, icon);//该键通常用于菜单,同时指定了要使用SMALL-ICONputValue(Action.SHORT_DESCRIPTION, "Set panel color to " + name.toLowerCase());//用来存储动作的简短 String 描述的键,用于工具提示文本。//toLowerCase使用默认语言环境的规则将此 String 中的所有字符都转换为小写putValue("color", c);}public void actionPerformed(ActionEvent event)//actionListener中的一个方法
      {Color c = (Color) getValue("color");buttonPanel.setBackground(c);}}
}

actionFrame

测试程序4:

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

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

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

mouse

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 cursorpublic MouseComponent(){squares = new ArrayList<>();//构造一个空列表current = null;addMouseListener(new MouseHandler());//添加鼠标监听器addMouseMotionListener(new MouseMotionHandler());//添加指定的鼠标移动侦听器,以接收发自此组件的鼠标移动事件。
   }public Dimension getPreferredSize() { return new Dimension(DEFAULT_WIDTH, DEFAULT_HEIGHT); }   //如果 preferredSize 已设置为一个非 null 值,则返回该值。如果 UI 委托的 getPreferredSize 方法返回一个非 null 值,则返回该值;public void paintComponent(Graphics g){Graphics2D g2 = (Graphics2D) g;// draw all squaresfor (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)//通过位置 (x,y) 和尺寸 (w x h) 定义的矩形。
   {for (Rectangle2D r : squares){if (r.contains(p)) return r;//测试指定的 Point2D 是否在 Shape 的边界内
      }return null;}/*** Adds a square to the collection.* @param p the center of the square*/public void add(Point2D p){double x = p.getX();//返回该图形的X,Y坐标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 squarecurrent = find(event.getPoint());if (current == null) add(event.getPoint());//若鼠标指针不在之前的矩形内,则点击鼠标时,重新画一个矩形
      }public void mouseClicked(MouseEvent event)//鼠标按键在组件上单击(按下并释放)时调用。
      {// remove the current square if double clickedcurrent = 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 rectangleif (find(event.getPoint()) == null) setCursor(Cursor.getDefaultCursor());//为指定的光标设置光标图像else setCursor(Cursor.getPredefinedCursor(Cursor.CROSSHAIR_CURSOR));//十字光标类型。
      }public void mouseDragged(MouseEvent event)//鼠标按键在组件上按下并拖动时调用。在释放鼠标按键前,MOUSE_DRAGGED 事件被连续地传递到发起该拖动的组件(而不管鼠标位置是否处于该组件的边界内)。
      {if (current != null){int x = event.getX();int y = event.getY();
//当发生鼠标事件时: MouseEvent类自动创建一个事件对象,以及事件发生位置的x和y坐标,作为事件返回值。// 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所示,点击停止按钮后,文本输入框不再变换同学姓名,此同学则是被点到的同学姓名。

图1 点名器启动界面

图2 点名器点名界面

 

 

package 点名器;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;//JLabel 对象可以显示文本、图像或同时显示二者。private JLabel jlb;private JButton jba;private static boolean flag = true;//定义一个静态常量并将其值设置为truepublic NameFrame() {this.setLayout(null);//类 Container 中的 setLayout,设置 LayoutManager。重写此方法,从而有条件地将调用转发到 contentPane
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, 22));jlb.setHorizontalAlignment(JLabel.CENTER);jlb.setVerticalAlignment(JLabel.CENTER);jlb.setBounds(150, 100, 120, 30);this.add(jba);//设置开始按钮的一些属性jba.setBounds(150, 150, 80, 26);//移动组件并调整其大小。由 x 和 y 指定左上角的新位置,由 width 和 height 指定新的大小。
jba.addActionListener(this);//将一个 ActionListener 添加到按钮中this.setTitle("点名器");this.setBounds(400, 400, 400, 300);this.setVisible(true);this.setDefaultCloseOperation(DISPOSE_ON_CLOSE);//调用任意已注册 WindowListener 的对象后自动隐藏并释放该窗体。
    }public void actionPerformed(ActionEvent e) {int i = 0;String names[] = new String[50];//创建一个数组,该数组的最大容量为50try {Scanner in = new Scanner(new File("D:\\studentnamelist.txt"));while (in.hasNextLine()) {//如果在此扫描器的输入中存在另一行,则返回 true。在等待输入信息时,此方法可能阻塞。扫描器不执行任何输入。 names[i] = in.nextLine();i++;//遍历名单
            }} catch (FileNotFoundException e1) {// TODO Auto-generated catch block
            e1.printStackTrace();}if (jba.getText() == "开始") {//返回按钮的文本jlb.setBackground(Color.BLUE);//设置组件的背景色flag = true;new Thread() {//分配新的 Thread 对象。这种构造方法与 Thread(null, null, gname) 具有相同的作用,其中 gname 是一个新生成的名称。自动生成的名称的形式为 "Thread-"+n,其中的 n 为整数。public void run() {while (NameFrame.flag) {Random r = new Random();int i = r.nextInt(47);jlb.setText(names[i]);//定义此组件将要显示的单行文本。如果 text 值为 null 或空字符串,则什么也不显示,此时为name则显示停止时的名字
                    }}}.start();//使该线程开始执行;Java 虚拟机调用该线程的 run 方法。jba.setText("停止");jba.setBackground(Color.ORANGE);} else if (jba.getText() == "停止") {flag = false;//当点击按钮的停止时,返回该按钮的名字,并且变量flag的布尔值为flasejba.setText("开始");//按钮的名字为开始jba.setBackground(Color.WHITE);//开始按钮的颜色为白色jlb.setBackground(Color.gray);//未开始点击开始按钮时,姓名输入框为灰色
        }}public static void main(String arguments[]) {new NameFrame();}
}

nameframe

在点名器的程序设计中,完全没有思路该如何写,在学长的实例程序上做了注释及稍许改动,但对于多线程还是没有理解该如何使用。

 实验总结:通过本周学习,我基本掌握了事件处理的基本原理及AWT事件模型的工作机制;掌握事件处理的基本编程模型;并用多种方法简化代码,在老师和学长的教导进一步

理解了匿名内部类,但对于 GUI界面组件观感设置方法还不太理解; 掌握了AbstractAction类的用法及GUI程序中鼠标事件处理技术。

转载于:https://www.cnblogs.com/li-xiaojing/p/10002768.html

李晓菁201771010114《面向对象程序设计(java)》第十三周学习总结相关推荐

  1. 201871010115——马北《面向对象程序设计JAVA》第二周学习总结

    项目 内容 这个作业属于哪个课程 https://www.cnblogs.com/nwnu-daizh/ 这个作业的要求在哪里 https://www.cnblogs.com/nwnu-daizh/p ...

  2. 《数据结构与面向对象程序设计》第1周学习总结

    20182316胡泊 2019-2020-1 <数据结构与面向对象程序设计>第1周学习总结 教材学习内容总结 简单java程序是有哪些部分组成的 Java程序好的排版布局是怎样的 程序开发 ...

  3. 201521123122 《java程序设计》第十三周学习总结

    ## 201521123122 <java程序设计>第十三周实验总结 ## 1. 本周学习总结 以你喜欢的方式(思维导图.OneNote或其他)归纳总结多网络相关内容. 2. 书面作业 1 ...

  4. 四十八.面向对象程序设计——Java语言第一周编程题:分数

    题目内容: 设计一个表示分数的类Fraction.这个类用两个int类型的变量分别表示分子和分母. 这个类的构造函数是: Fraction(int a, int b) 构造一个a/b的分数. 这个类要 ...

  5. 201521123022 《Java程序设计》 第十三周学习总结

    1. 本周学习总结 2. 书面作业 Q1. 网络基础 Q1.1 比较ping www.baidu.com与ping cec.jmu.edu.cn,分析返回结果有何不同?为什么会有这样的不同? 前者IP ...

  6. 201621123053《Java程序设计》第十三周学习笔记文章

    42#1. 本周学习总结 以你喜欢的方式(思维导图.OneNote或其他)归纳总结多网络相关内容. 2. 为你的系统增加网络功能(购物车.图书馆管理.斗地主等)-分组完成 为了让你的系统可以被多个用户 ...

  7. 201771010118马昕璐《面向对象程序设计java》第八周学习总结

    第一部分:理论知识学习部分 1.接口 在Java程序设计语言中,接口不是类,而是对类的一组需求描述,由常量和一组抽象方法组成.Java为了克服单继承的缺点,Java使用了接口,一个类可以实现一个或多个 ...

  8. 【Java】《面向对象程序设计——Java语言》Castle代码修改整理

    前言 最近闲来无事刷刷MOOC,找到以前看的浙大翁凯老师的<面向对象程序设计--Java语言>课程,重新过一遍仍觉受益颇深. 其中有一个Castle的例子,思路很Nice但代码很烂,翁凯老 ...

  9. 张季跃 201771010139《面向对象程序设计(java)》第十三周学习总结

    张季跃 201771010139<面向对象程序设计(java)>第十三周学习总结 实验部分: 1.实验目的与要求 (1) 掌握事件处理的基本原理,理解其用途: (2) 掌握AWT事件模型的 ...

最新文章

  1. 【Codeforces】716B Complete the Word (26个字母)
  2. 大龄程序员刚迈过了 35 岁这个“坎儿”,和大家说点儿心里话
  3. 【原创】POSTGRESQL 分区表初次体验
  4. DeepMind助力Waymo!提升自动驾驶AI准确率,还能加快模型训练
  5. 裸奔浏览器_大概是最好用的隐私浏览器 - Firefox Focus
  6. 在移动了用户数据时Android平台的路径设置
  7. hdmi接口有什么用_你的电脑为什么没有HDMI接口?
  8. leetcode114. 二叉树展开为链表
  9. Python中使用PhantomJS抓取Javascript网页数据
  10. 每天进步一点点《PCA的简要学习》
  11. GP学习(三)—How to run a geoprocessing tool
  12. 搜python题_python知识点汇总(可以搜Python题答案的APP)
  13. python selenium --一些常用方法
  14. css连续选取几个li_CSS高级选择器:nth-child()应用大全
  15. 由于Web服务器上的“ISAPI 和 CGI 限制”列表设置,无法提供您请求的页面(http error 404.2、iis、0x800704ec)...
  16. ubuntu phpmyadmin php5.3,ubuntu中怎么下载安装phpmyadmin
  17. python-web开发(一)知识储备准备
  18. 阻碍你成功的五个不良习惯
  19. C4D中使用Redshift渲染器翻转贴图
  20. 划分非独立同分布(Non-IID)数据集

热门文章

  1. 【电路补习笔记】2、电容的参数与选型
  2. 【STC15库函数上手笔记】10、EEPROM
  3. 运行shell:windows命令,及显示桌面.scf的问题
  4. 微软面试题:有100万个数字(1到9),其中只有1个数字重复2次,如何快速找出该数字
  5. 微信小程序保存图片到相册;uni-app小程序保存网络图片到相册;小程序保存图片到相册拒绝授权后重新拉起授权;保存图片到系统相册;小程序保存图片测试可以,真机保存图片失败
  6. openwrt gpio控制与使用
  7. 前端学习(3050):vue+element今日头条管理-表格组件基本使用
  8. 1社会心理学---感知情境
  9. [vue-element] ElementUI是怎么做表单验证的?在循环里对每个input验证怎么做呢?
  10. 前端学习(2585):vue-cli创建项目