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 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;//宽300 private static final int DEFAULT_HEIGHT = 200;//高200public ButtonFrame()
{ setSize(DEFAULT_WIDTH, DEFAULT_HEIGHT);// 创建按钮
JButton orangeButton = new JButton("Orange");//创建一个带文本的按钮。 JButton blueButton = new JButton("blue"); JButton greyButton = new JButton("Grey");buttonPanel = new JPanel();
// 向面板添加按钮
buttonPanel.add(orangeButton); buttonPanel.add(blueButton); buttonPanel.add(greyButton);// 向框架添加面板
add(buttonPanel);// 创建按钮操作
ColorAction orangeAction= new ColorAction(Color.ORANGE); ColorAction blueAction = new ColorAction(Color.BLUE); ColorAction greyAction = new ColorAction(Color.GRAY);// 将操作与按钮相关联
orangeButton.addActionListener(orangeAction); blueButton.addActionListener(blueAction); greyButton.addActionListener(greyAction); }/**
* 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); } }}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);//界面的可见 }); }}
改进后
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();
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); } } }
再度改进:(匿名内部类)
测试程序2:
l 在elipse IDE中调试运行教材449页程序11-2,结合程序运行结果理解程序;
l 在组件观感设置代码处添加注释;
l 了解GUI程序中观感的设置方法。
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();
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() { public void actionPerformed(ActionEvent event) { buttonPanel.setBackground(backgroundColor); } }); }}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();
//为了配置菜单或为了初始应用程序设置而提供关于已安装的 LookAndFeel 的少量信息 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); SwingUtilities.updateComponentTreeUI(this); pack(); } catch (Exception e) { e.printStackTrace(); } }); }}
测试程序3:
l 在elipse IDE中调试运行教材457页-458页程序11-3,结合程序运行结果理解程序;
l 掌握AbstractAction类及其动作对象;
l 掌握GUI程序中按钮、键盘动作映射到动作对象的方法。
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();
// 定义的行为
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);//为这些操作添加按钮
buttonPanel.add(new JButton(yellowAction)); buttonPanel.add(new JButton(blueAction)); buttonPanel.add(new JButton(redAction));// 向框架添加面板
add(buttonPanel);//将Y、B和R键与名称关联起来
InputMap imap = buttonPanel.getInputMap(JComponent.WHEN_ANCESTOR_OF_FOCUSED_COMPONENT); imap.put(KeyStroke.getKeyStroke("ctrl Y"), "panel.yellow"); imap.put(KeyStroke.getKeyStroke("ctrl B"), "panel.blue"); imap.put(KeyStroke.getKeyStroke("ctrl R"), "panel.red");// 将名称与动作关联起来
ActionMap amap = buttonPanel.getActionMap(); 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); 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); } }}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); }); }}
测试程序4:
l 在elipse IDE中调试运行教材462页程序11-4、11-5,结合程序运行结果理解程序;
l 掌握GUI程序中鼠标事件处理技术。
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; //包含鼠标光标的正方形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); }/**
* 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) { //如果光标不在正方形内,则添加一个新的正方形 current = find(event.getPoint()); if (current == null) add(event.getPoint()); }public void mouseClicked(MouseEvent event)
{ //如果双击,则删除当前方块 current = find(event.getPoint()); if (current != null && event.getClickCount() >= 2) 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 / 2, y - SIDELENGTH / 2, SIDELENGTH, SIDELENGTH); repaint(); } } } }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(); }}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); }); }}
实验2:结对编程练习
利用班级名单文件、文本框和按钮组件,设计一个有如下界面(图1)的点名器,要求用户点击开始按钮后在文本输入框随机显示2017级网络与信息安全班同学姓名,如图2所示,点击停止按钮后,文本输入框不再变换同学姓名,此同学则是被点到的同学姓名。
package 实验十三;
import java.awt.Color;
import java.awt.Font;
import java.awt.Rectangle;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.image.BufferedImage;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.Random;
import java.util.Scanner;
import javax.imageio.ImageIO;
import javax.swing.ImageIcon;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JTextArea;
public class 点名器 extends JFrame{
private static final long serialVersionUID = 1L;
JFrame jframe= new JFrame("窗体生成");
JPanel jpanel=null;
JPanel imagePanel = null;
BufferedImage image= null;
JLabel label3 = new JLabel();
ImageIcon background = new ImageIcon();
JTextArea jtext = new JTextArea();
JButton jbutton1=new JButton("开始");
JButton jbutton2=new JButton("暂停");
JButton jbutton3=new JButton("确定");
String strPath = "";
public static boolean flag = true;//判断开始按钮是否被点过
private static Thread t;
private int count = 0;
public 点名器(){
//添加背景图片
try {
image=ImageIO.read(new File("F:\\图片\\95.jpg"));
} catch (IOException e) {
e.printStackTrace();
}
background = new ImageIcon(image);
//把背景图片显示在一个标签里面
JLabel label = new JLabel(background);
//把标签的大小位置设置为图片刚好填充整个面板
label.setBounds(0,0,450,400);
//把内容窗格转化为JPanel,否则不能用方法setOpaque()来使内容窗格透明
imagePanel = (JPanel)getContentPane();
imagePanel.setOpaque(false);
//把背景图片添加到分层窗格的最底层作为背景
getLayeredPane().add(label,new Integer(Integer.MIN_VALUE));
//添加文字
jpanel = (JPanel)this.getContentPane();//每次添加必须要加的语句
JLabel label2 = new JLabel("请输入TXT文本路径:");
Font font = new Font("",Font.BOLD,30);
label2.setFont(font);
label2.setForeground(Color.yellow);
label2.setBounds(20,50,450,100);
jpanel.add(label2);
//添加按钮
jpanel=(JPanel)this.getContentPane();
jpanel.setLayout(null);
//(左,上,宽,高)
jbutton3.setBounds(new Rectangle(330,180,60,20));
jbutton3.addActionListener(new TextValue(this));
jpanel.add(jbutton3);
//添加文本框(左,上,宽,高)
jtext.setBounds(40, 180, 260, 20);
jpanel.add(jtext);
}
/**
* 重写构造器
*/
public 点名器(String str){
//将路径传入开始按钮
strPath = str;
//添加背景图片
try {
image=ImageIO.read(new File("F:\\图片\\95.jpg"));
} catch (IOException e) {
e.printStackTrace();
}
background = new ImageIcon(image);
//把背景图片显示在一个标签里面
JLabel label = new JLabel(background);
//把标签的大小位置设置为图片刚好填充整个面板
label.setBounds(0,0,450,400);
//把内容窗格转化为JPanel,否则不能用方法setOpaque()来使内容窗格透明
imagePanel = (JPanel)getContentPane();
imagePanel.setOpaque(false);
//把背景图片添加到分层窗格的最底层作为背景
getLayeredPane().add(label,new Integer(Integer.MIN_VALUE));
//添加提示文字
jpanel = (JPanel)this.getContentPane();//每次添加必须要加的语句
JLabel label2 = new JLabel("点名开始啦!!!");
Font font = new Font("",Font.BOLD,30);
label2.setFont(font);
label2.setForeground(Color.yellow);
label2.setBounds(100,20,450,100);
jpanel.add(label2);
//显示名字信息
label3.setBounds(150,120,450,100);
//设置字体颜色
label3.setForeground(Color.yellow);
//添加按钮
jpanel=(JPanel)this.getContentPane();
jpanel.setLayout(null);
jbutton1.setBounds(new Rectangle(100,300,75,25));
jpanel.add(jbutton1);
jbutton1.addActionListener(new Action(this));
jbutton2.setBounds(new Rectangle(250,300,75,25));
jpanel.add(jbutton2);
jbutton2.addActionListener(new Stop(this));
}
/**
* 从控制台输入路径
*/
public static String InputPath(){
String str ="";
System.out.println("请输入TXT文本路径:");
Scanner sc= new Scanner(System.in);
str = sc.nextLine();
return str;
}
/**
* 读取文档数据
* @param filePath
* @return
*/
public static String ReadFile(String filePath){
String str = "";
try {
String encoding="GBK";
File file = new File(filePath);
if(file.isFile()&&file.exists()){
InputStreamReader reader =
new InputStreamReader(new FileInputStream(file),encoding);
BufferedReader bufferedReader = new BufferedReader(reader);
String lineTxt = "";
while((lineTxt = bufferedReader.readLine()) != null){
str+=lineTxt+";\n";
}
reader.close();
}else{
System.out.println("找不到指定的文件");
}
}catch (Exception e) {
System.out.println("读取文件内容出错");
e.printStackTrace();
}
return str;
}
/**
* 将字符串转换为String数组
*/
public static String[] ChangeType(String str){
ArrayList<String> list=new ArrayList<String>();
String[] string = str.split(";");
return string;
}
/**
* main方法
* @param args
*/
public static void main(String args[]){
点名器 jframe=new 点名器();
jframe.setTitle("点名器");
jframe.setSize(450,400);
jframe.setVisible(true);
jframe.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
jframe.setResizable(false);
jframe.setLocationRelativeTo(null);
System.out.println();
}
/**
* 点击确定按钮后的方法
*/
public void chooseValue(ActionEvent e){
String str = "";
str = jtext.getText();
if(str != "" || str != null){
点名器 jframe = new 点名器(str);
jframe.setTitle("点名器");
jframe.setSize(450,400);
jframe.setVisible(true);
jframe.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
jframe.setResizable(false);
jframe.setLocationRelativeTo(null);
System.out.println(str);
}
}
/**
* 点击开始按钮后的方法
*/
public void actionRun(ActionEvent e){
if(flag){
//线程开始
t = new Thread(new Runnable(){
public void run(){//
while(count<=10000){
//文件路径
String strTest = strPath;
//开始读取数据
String strRead = ReadFile(strTest);
//将读取到的数据变为数组
String[] strc = ChangeType(strRead);
//获取随机的姓名
Random random = new Random();
int a = 0;
a = random.nextInt(strc.length-1);
String str = strc[a];
System.out.println("输出名字为:"+str);
label3.setFont(new java.awt.Font(str,1,60));
//设置名字标签的文字
label3.setText(str);
try{
t.sleep(20);//使线程休眠50毫秒
}catch(Exception e){
e.printStackTrace();
}
count+=1;//显示次数
}
}
});
t.start();
//设置字体颜色
jpanel.add(label3);
flag = false;
}
flag = false;
}
/**
* 点击暂停按钮后的方法
*/
public void stopRun(ActionEvent e){
if(!flag){
t.stop();
flag = true;
}
flag = true;
}
}
/**
*确定按键监控类
*/
class TextValue implements ActionListener {
private 点名器 startJFrame;
TextValu(点名器 startJFrame) {
this.startJFrame = startJFrame;
}
public void actionPerformed(ActionEvent e) {
startJFrame.chooseValue(e);
startJFrame.setVisible(false);
}
}
/**
*开始按键监控类
*/
class Action implements ActionListener {
private 点名器 jFrameIng;
Action(点名器 jFrameIng) {
this.jFrameIng = jFrameIng;
}
public void actionPerformed(ActionEvent e) {
jFrameIng.actionRun(e);
}
}
/**
*暂停按键监控类
*/
class Stop implements ActionListener {
private 点名器 jFrameIng;
Stop(点名器 jFrameIng) {
this.jFrameIng = jFrameIng;
}
public void actionPerformed(ActionEvent e) {
jFrameIng.stopRun(e);
}
}
本周学习总结:
1,事件监听器
事件监听器是类库中的一组接口,每种事件类都有一个负责监听这种事件对象的接口。接口中定义了处理该事件的抽象方法。
接口只是一个抽象定义,要想使用必须实现它。所以每次对事件进行处理是调用对应接口的实现类中的方法。当事件源产生事件并生成事件对象,该对象被送到事件处理器中,处理器调用接口实现类对象中的相应方法来处理该事件。 要想启动相应的事件监听器必须在程序中注册它。事件的种类
JAVA处理事件响应的类和监听接口大多位于AWT包中。在java.swing.event包中有专门用于Swing组件的事件类和监听接口。
AWT事件类继承自AWTEvent,他们的超类是EventObject。在AWT事件中,事件分为低级事件和语义事件。语义事件是对某些低级事件的一种抽象概括,是单个或多个低级事件的某些特例的集合。 常用低级事件有:事件 说明
KeyEvent 按键按下和释放产生该事件MouseEvent 鼠标按下、释放、拖动、移动产生该事件FocusEvent 组件失去焦点产生该事件WindowEvent 窗口发生变化产生该事件常用语义事件有:事件 说明
ActionEvent 当单击按钮、选中菜单或在文本框中回车等产生该事件ItemEvent 选中多选框、选中按钮或者单击列表产生该事件常用事件和事件监听器如下:事件类型 对应的监听器 监听器接口中的抽象方法
Action ActionListener actionPerformed(ActionEvent e)Mouse MouseListener mouseClicked(MouseEvent e)、mouseEntered(MouseEvent e)、mouseExited(MouseEvent e)、mousePressed(MouseEvent e)、mouseReleased(MouseEvent e)MouseMotion MouseMotionListener mouseDragged(MouseEvent e)、mouseMoved(MouseEvent e)Item ItemListener itemStateChanged(ItemEvent e)Key KeyListener keyPressed(KeyEvent e)、keyReleased(KeyEvent e)、keyTyped(KeyEvent e)Focus FocusListener focusGained(FocusEvent e)、focusLost(FocusEvent e)Window WindowListener windowActivated(WindowEvent e)、windowClosed(WindowEvent e)、windowClosing(WindowEvent e)、windowDeactivated(WindowEvent e)、windowDeiconified(WindowEvent e)、windowIconified(WindowEvent e)、windowOpened(WindowEvent e)Component ComponentListener componentHidden(ComponentEvent e)、componentMoved(ComponentEvent e)、componentResized(ComponentEvent e)、componentShown(ComponentEvent e)Text TextListener textValueChanged(TextEvent e)事件适配器事件适配器其实就是一个接口的实现类,实际上适配器类只是将监听接口方法中的方法全部实现成空方法。这样在定义事件监听器时就可以继承该实现类,并重写所需要的方法,不必实现覆盖所有方法了。常用的事件适配器类有如下击中
适配器 说明
MouseAdapter 鼠标事件适配器WindowAdapter 窗口事件适配器KeyAdapter 键盘事件适配器FocusAdapter 焦点适配器MouseMotionAdapter 鼠标移动事件适配器ComponentAdapter 组件源适配器ContainerAdapter 容器源事件适配器