项目

内容

这个作业属于哪个课程

https://www.cnblogs.com/nwnu-daizh/

这个作业的要求在哪里

https://www.cnblogs.com/zyja/p/11918987.html

作业学习目标

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

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

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

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

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

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

1.总结第十一章理论知识

11.1 事件处理基础

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

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

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

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

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

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

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

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

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

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

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

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

示例: ActionListener listener = ...;

JButton button = new JButton("OK");

button.addActionListener(listener);

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

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

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

(1) 点击按钮

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

(3) 选择菜单项;

11.2  监听器接口的实现

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

• 监听器接口中方法实现:

class Mylistener implements ActionListener

{

public void actionPerformed(ActionEvent event)    {...}

}

2. 命令按钮JButton的API

• 创建按钮对象

JButton 类常用的构造方法:

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

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

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

• 按钮对象的常用方法

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

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

11.3  用匿名类,lambda表达式简化程序

1)使用字符串构造按钮对象

2)把按钮添加到面板上

3)用对应的颜色构造一个动作监听器

4)注册动作监听器

11.4 改变观感的方法

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

1)在Java安装的子目录jre/lib下的文件swing.properties中,将属性swing.defaultlaf设置为所希望的观感类名  swing.defaultlaf = com.sun.java.swing.plaf.motif.MotifLookAndFeel

2)调用静态的UIMananger.setLookAndFeel方法,动态的改变观感,提供所想要的观感类名,再调用静态方法SwingUtilities.updateComponenetTreeUI来刷新全部组件集。

11.5 适配器类

捕获窗口事件的监听器:  WindowListener listener = .....;

frame.addWindowListener(listener);

11.6 动作事件

1.  在AWT时间模型中,可设置用不同方式下达命令,其操作动作都是一样的。

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

3. 动作对象是一个封装下列内容的对象: 命令的说明和执行命令所需要的参数。

4. Action 是一个接口,而不是一个类。

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

6. 在动作处理应用中,可以直接扩展AbstractActon类,并在扩展类中实现actionPerformed方法。

11.7 击键关联映射

1. 将一个动作对象添加到击键中,以便让用户敲击键盘命令来执行这个动作。

2. 将动作与击键关联起来,需生成keyStroke类对象

11.8 鼠标事件

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

- 鼠标第一次被按下时调用mousePressed方法;

- 鼠标被释放是调用mouseReleased方法;

- 两个动作完成之后,调用mouseClicked方法;

2. 鼠标在组件上移动时,会调用mouseMoved方法

3. 如果鼠标在移动的时候还按下了鼠标,则会调用mouseDragged方法

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

5. MouseEvent 类中的重要方法:

- public int getX();

- public int getY();

- public Point getPoint();

- public int getClickCount();

6. 设置光标:

11.9  AWT事件继承层次

1. 所有的事件都是由java.util包中的EventObject类扩展而来

2. AWT将事件分为低级(low-level)事件(形成语义事件的事件)和语义事件(表达用户动作的事件)

3. AWT常用的语义事件:

- ActionEvent(对应按钮点击,菜单选择,选择列表项或在文本域中键入ENTER)

- AdjustmentEvent(用户调节滚动条)

- ItemEvent(用户从复选框或列表项中选择一项)

4. 低层事件

-KeyEvent(一个键被按下或被释放)

-MouseEvent(鼠标被按下,释放,移动或拖动)

-MouseWheelEvent(鼠标滚轮被传动)

-FocusEvent(某个组件获得或失去焦点)

-WindowEvent(窗口状态改变)

2、实验内容和步骤

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

测试程序1

ButtonFrame.java:

 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 = ;
private static final int DEFAULT_HEIGHT = ; 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);
} //当按钮被点击时,将面板的颜色设置为指定的颜色,这个颜色存储在监听器类中
private class ColorAction implements ActionListener//实现监听器接口
{
private Color backgroundColor; public ColorAction(Color c)
{
backgroundColor = c;
} public void actionPerformed(ActionEvent event)//实现actionPerformed方法,接收事件对象
{
buttonPanel.setBackground(backgroundColor);
}
}
}
 ButtonTest.java:
 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(() -> {
ButtonFrame frame = new ButtonFrame();
frame.setTitle("ButtonTest"); //给出框架的标题
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setVisible(true);//该框架是可见的
});
}
}

用lambda表达式简化程序;

 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 = ;
private static final int DEFAULT_HEIGHT = ; public void makeButton(String name,Color backgroundColor)
{
JButton button = new JButton(name);
buttonPanel.add(button);
button.addActionListener((e)->{
buttonPanel.setBackground(backgroundColor);
});
} public ButtonFrame()
{
setSize(DEFAULT_WIDTH, DEFAULT_HEIGHT); makeButton("yellow", Color.YELLOW);
makeButton("blue", Color.BLUE);
makeButton("red", Color.RED);
buttonPanel = new JPanel(); // 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); }
/**
* 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);
}
}
}

运行结果如下:

            

测试程序2

PlafFrame.java
 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)
{
// 增加按钮到面板 JButton button = new JButton(name);
buttonPanel.add(button); //设置按钮动作
button.addActionListener(event -> {
// 按钮动作:切换到新的外观和感觉
try
{
UIManager.setLookAndFeel(className);//调用静态的UIManager.setLookAndFeel(className)方法,并提供了所想要的观感类名“className"
SwingUtilities.updateComponentTreeUI(this);//调用静态方法 SwingUtilities.updateComponentTreeUI()来刷新全部的组件集
pack();
}
catch (Exception e)
{
e.printStackTrace();
}
});
}
}

Plaf.Test.java:

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

运行结果如下:

          

       

测试程序3:

 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 = ;
private static final int DEFAULT_HEIGHT = ; public ActionFrame()
{
setSize(DEFAULT_WIDTH, DEFAULT_HEIGHT); buttonPanel = new JPanel(); //定义动作 ColorAction yellowAction = new ColorAction("Yellow", new ImageIcon("yellow-ball.gif"), Color.YELLOW);
ColorAction blueAction = new ColorAction("Blue", new ImageIcon("blue-ball.gif"), Color.BLUE);
ColorAction 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 panel to frame
add(buttonPanel); // 将Y,B,R与姓名关联 InputMap inputMap = buttonPanel.getInputMap(JComponent.WHEN_ANCESTOR_OF_FOCUSED_COMPONENT);//得到顶层组件的WHEN_ANCESTOR_OF_FOCUSED_COMPONENT输入映射
inputMap.put(KeyStroke.getKeyStroke("ctrl Y"), "panel.yellow");
inputMap.put(KeyStroke.getKeyStroke("ctrl B"), "panel.blue");
inputMap.put(KeyStroke.getKeyStroke("ctrl R"), "panel.red"); // 将姓名与动作关联
ActionMap actionMap = buttonPanel.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)
{
Color color = (Color) getValue("color");
buttonPanel.setBackground(color);
}
}
}

ActionTest.java:

 import java.awt.*;
import javax.swing.*;
public class ActionTest
{
public static void main(String[] args)
{
EventQueue.invokeLater(() -> {
ActionFrame frame = new ActionFrame();
frame.setTitle("ActionTest");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setVisible(true);
});
}
}

运行结果如下:

            

测试程序4

 package 第13周;

 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 = ;
private static final int DEFAULT_HEIGHT = ; private static final int SIDELENGTH = ;
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);
} public Rectangle2D find(Point2D p)
{
for (Rectangle2D r : squares)
{
if (r.contains(p)) return r;
}
return null;
} public void add(Point2D p)
{
double x = p.getX();
double y = p.getY(); current = new Rectangle2D.Double(x - SIDELENGTH / , y - SIDELENGTH / , SIDELENGTH,
SIDELENGTH);
squares.add(current);
repaint();
} 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() >= ) 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 / , y - SIDELENGTH / , SIDELENGTH, SIDELENGTH);
repaint();
}
}
}
}
 package 第13周;

 import javax.swing.*;

 /**
*
包含用于测试鼠标操作的面板的框架
*/
public class MouseFrame extends JFrame
{
public MouseFrame()
{
add(new MouseComponent());
pack();
}
}
 package 第13周;

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

运行结果如下:

实验2:结对编程练习

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

整体思路:点名器需要有一个定时器,还要有一个循环,设计一个GUI图形界面,读取文件里面学生的姓名,在actionPerformed方法中,当jButton的内容为"begin"时,启动定时器,利用随机数来得到学生的姓名,当jButton的内容为"stop"时,调用Timer类对象的cancel方法停用定时器,由此得到。

 package tuxing;
import java.awt.Color;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.BufferedInputStream;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.StringBufferInputStream;
import java.util.ArrayList;
import java.util.Timer;
import java.util.TimerTask; import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel; public class ButtonFrame extends JFrame {
private JPanel buttonPanel;
private static final int DEFAULT_WIDTH = ;
private static final int DEFAULT_HEIGHT = ;
private JButton jButton;
private ArrayList<String> arrayList; public ButtonFrame() {
setSize(DEFAULT_WIDTH, DEFAULT_HEIGHT);
buttonPanel = new JPanel();
buttonPanel.setLayout(null);
buttonPanel.setBackground(Color.blue);
add(buttonPanel);
jButton = new JButton("Begin");
jButton.setBackground(Color.blue);
jButton.setBounds(, , , );
jButton.setBounds(, , , );
arrayList = new ArrayList<>();
//读文件
File file = new File("2019studentlist.txt");
FileInputStream fis;
try {
fis = new FileInputStream(file);
InputStreamReader in = new InputStreamReader(fis);
BufferedReader buf = new BufferedReader(in);
String readLine;
while ((readLine = buf.readLine())!=null) {
arrayList.add(readLine);
}
} catch (FileNotFoundException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
} catch (IOException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
} jButton.addActionListener(new ActionListener() {
Timer timer; public void actionPerformed(ActionEvent e) {
if (jButton.getText().equals("Begin")) {
timer = new Timer();;
TimerTask timerTask = new TimerTask() {
public void run() {
jButton.setText("Stop");
jButton.setBackground(Color.red);
jButton.setText(arrayList.get((int) (Math.random() * )));
}
};
timer.schedule(timerTask, , );
}
if (jButton.getText().equals("Stop")) {
timer.cancel();
jButton.setText("Begin");
jButton.setBackground(Color.blue);
}
}
});
buttonPanel.add(jButton);
buttonPanel.add(jButton);
add(buttonPanel); }
}

运行结果:

         

结对编程照片:

实验总结:本次实验中,主要学到了事件源,事件监听器,和事件对象,以及动作事件,在事件监听器中,必须要实现actionPerform()方法,用来接收事件对象。创建按钮对象中JButton类的构造方法很常用,也很重要。用匿名内部类和lambda表达式简化程序是一个很重要的方法,我掌握的一般,会继续努力。观感和鼠标事件我觉得比前面的难一点,通过测试程序和看书,还是知道了一点点,最后的结对编程很难,通过网上查找,寻求其他同学的帮助,然后还有自己琢磨,也还差不多了,但是问题还是很多,我也会自己抓紧的。

最新文章

  1. jQuery初探 jQuery选取和操纵元素的特点
  2. for+next()实现数组的遍历及while list each 的使用
  3. matplotlib 随记
  4. 【Codeforces 722C】Destroying Array (数据结构、set)
  5. Redis_字典
  6. CSS简写及如何优化技巧
  7. jquery实现显示和隐藏toggle()方法的使用
  8. INotifyPropertyChanged(监听数据),当数据改变时调用
  9. 简单Elixir游戏服设计- 游戏玩法介绍
  10. PSP总结报告
  11. Flip String to Monotone Increasing LT926
  12. HBase describe table 参数说明
  13. element vuex 语音播报
  14. 使用mui.js实现下拉刷新
  15. Spring+mvc错误
  16. PDO中的预处理
  17. [Spark RDD_add_1] groupByKey &amp; reduceBykey 的区别
  18. 李炎恢的课程中心(JQUERY视频)
  19. 【第八章】MySQL数据库备份—逻辑备份
  20. netty 基础知识

热门文章

  1. Django的下载与创建。
  2. ln -s 文件夹变成文件(txt) / linux 链接出错
  3. &lt;String&gt; 186 293 294 249
  4. ES2019 的新特性
  5. 近似计算一个对象在js占用内存
  6. PostgreSQL CentOS 7 安装配置
  7. Vue动态修改网页标题
  8. matplotlib基础
  9. OpenGL入门1.3:着色器 GLSL
  10. QT+OpenGL(02)-- zlib库的编译