201871010136—赵艳强《面向对象程序设计(java)》第十三周学习总结

201871010136—赵艳强《面向对象程序设计(java)》第十三周学习总结

 

博文正文开头格式:(2分)

项目

内容

《面向对象程序设计(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程序中鼠标事件处理技术。

随笔博文正文内容包括:

第一部分:总结第十一章理论知识(35分)

第11章 事件处理

一、 事件处理基础

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

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

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

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

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

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

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

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

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

(h)适配器类:当程序用户试图关闭一个框架窗口时,Jframe对象就是WindowEvent的事件源。

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

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

处理按钮点击事件:对于GUI的应用程序来说,事件处理是必不可少的,因此我们需要熟练地掌握事件处理模型。对于事件我们需要了解两个名词:事件源对象与监听器对象。从字面上我们就可以理解个大概,下面我们系统说明一下:监听器对象是一个实现了特定监听器接口(listener interface)的类的实例,事件源是一个能够注册监听器对象并发送事件对象的对象,事件发生时,事件源将事件对象传递给所有注册的监听器,监听器对象将利用事件对象中的信息决定如何对事件做出相应

二、简洁的指定监听器

监听器对象就是一个实现了特定监听器接口的类的实例,那么监听器接口就是我们所关心的问题了。在监听器接口的最顶层接口是java.util.EventListener,这个接口是所有事件侦听器接口必须扩展的标记接口。感到诧异的是这个接口完全是空的,里面没有任何的抽象方法的定义,查看源代码里面空空如也啊!

事件监听器类(监听器对象所属的类)必须实现事件监听器接口或继承事件监听器适配器类。

事件监听器接口定义了处理事件必须实现的方法。

事件监听器适配器类是对事件监听器接口的简单实现。目的是为了减少编程的工作量。

  事件监听器的接口命名方式为:XXListener,而且,在java中,这些接口已经被定义好了。用来被实现,它定义了事件处理器(即事件处理的方法原型,这个方法需要被重新实现)。

例如:ActionListener接口、MouseListener接口、WindowListener接口、KeyListener接口、ItemListener接口、MouseMotionListener接口、FocusListener接口、ComponentListener接口等

三、改变观感

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

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

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

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

四、适配器类

1.当程序用户试图关闭一个框架窗口时,JFrame对象就是WindowEvent的事件源。

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

  窗口监听器必须是实现WindowListener接口的类的一个对象,WindowListener接口中有七个方法,它们的名字是自解释的。

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

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

3.扩展WindowAdapter类,继承六个空方法,并覆盖WindowClosing()方法:

     class Terminator extends WindowAdapter{

     public void windowClosing(WindowEvente){

     System.exit(0);}}

4.可将一个Terminator对象注册为事件监听器:WindowListener listener=new Terminator();frame.addWindowListener(listener);

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

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

五、动作

(a) 激活一个命令可以有多种方式,如用户可以通过 菜单、击键或工具栏上的按钮选择特定的功能。 

(b) 在AWT事件模型中,无论是通过哪种方式下达命 令(如:点击按钮、菜单选项、按下键盘),其 操作动作都是一样的。

(c)动作接口及其类:Swing包提供了非常实用的机制来封装命令,并将它们连接到多个事件源,这就是Action接口。

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

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

六、 鼠标事件

(a)鼠标事件 – MouseEvent 

(b)鼠标监听器接口 – MouseListener – MouseMotionListener 

(c) 鼠标监听器适配器 – MouseAdapter – MouseMotionAdapter

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

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

2.鼠标被释放时调用mouseReleased方法;

3.两个动作完成之后,调用mouseClicked方法。

(e)鼠标在组件上移动时,会调用mouseMoved方法。

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

(g)监听鼠标点击事件,实现MouseListener接口.

七、AWT事件继承层次

(a) 所有的事件都是由java.util包中的EventObject 类扩展而来。 

(b) AWTEevent 是所有AWT 事件类的父类, 也是 EventObject的直接子类。 

(c) 有些Swing组件生成其他类型的事件对象,一般直 接 扩 展 于 EventObject, 而不是AWTEvent,位于 javax.swing.event.*。

(d) 事件对象封装了事件源与监听器彼此通信的事件 信息。在必要的时候,可以对传递给监听器对象的 事件对象进行分析。

第二部分:实验部分

实验1:测试程序1(5分)

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
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);
  
      // 创建了三个按钮对象
      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);
   }
  
   /**
    * An action listener that sets the panel's background color.
    */
   private class ColorAction implements ActionListener
   //ColorAction类后面实现了一个监听器接口类ActionListener
   {
      private Color backgroundColor;
 //Color 类用于封装默认 sRGB 颜色空间中的颜色,或者用于封装由 ColorSpace 标识的任意颜色空间中的颜色
  
      public ColorAction(Color c)
      {
         backgroundColor = c;
      }
  
      public void actionPerformed(ActionEvent event)
      {
         buttonPanel.setBackground(backgroundColor);
      }
   }
}

  

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
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)
   {
       //lambda表达式
      EventQueue.invokeLater(() -> {
         JFrame frame = new ButtonFrame();
         frame.setTitle("ButtonTest");
         //setTitle表示将此窗体的标题设置为制定的字符串
         frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
         //根据参数的值显示或隐藏窗口
         frame.setVisible(true);
      });
   }
} 

用lambda表达式简化:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
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*2;
    private static final int DEFAULT_HEIGHT = 200*2;
  
    public ButtonFrame() {
        setSize(DEFAULT_WIDTH, DEFAULT_HEIGHT);
        //用new运算符调用构造器
        buttonPanel = new JPanel();
    //创建按钮生成了三个按钮对象
        makeButton("黄色", Color.yellow);
        makeButton("蓝色", Color.blue);
        makeButton("红色", Color.red);
        add(buttonPanel);
    }
    protected void makeButton(String name,Color backgound) {
        // 创建按钮
        JButton button = new JButton(name);
        // 向面板添加按钮
        buttonPanel.add(button);
        // 创建按钮操作
         
        button.addActionListener(new ActionListener() {
              
            public void actionPerformed(ActionEvent e) {
                // TODO 自动生成的方法存根
                buttonPanel.setBackground(backgound);
            }
        });
        //通过lambad表达式实现
        button.addActionListener((e)->{
            buttonPanel.setBackground(backgound);
        });   
    }  
}

运行结果如下:

测试程序2:

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

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

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

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
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);
      });
   }
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.SwingUtilities;
import javax.swing.UIManager;
 
/**
 * 带有按钮面板的框架,用于更改外观和感觉
 */
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();
   }
 
   /**
    * 创建一个按钮来更改可插入的外观.
    * @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 //可能出错的代码放入try子句中
         {
            UIManager.setLookAndFeel(className);
            SwingUtilities.updateComponentTreeUI(this);
            pack();
         }
         catch (Exception e)
         {
            e.printStackTrace();
         }
      });
   }
}

运行结果:

测试程序3:

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

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

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

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
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(() -> {//lamda表达式
         var frame = new ActionFrame();
         frame.setTitle("ActionTest");//设置标题
         frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);//设置关闭操作
         frame.setVisible(true);//设置可见性
      });
   }
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
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//继承关系,ActionFrame的父类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();
 
      // 定义按钮
      var yellowAction = new ColorAction("Yellow"new ImageIcon("yellow-ball.gif"),
            Color.YELLOW);
      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));
      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);
      inputMap.put(KeyStroke.getKeyStroke("ctrl Y"), "panel.yellow");
      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();
      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");
         buttonPanel.setBackground(color);
      }
   }
}
 

程序运行时只需同时按Ctrl+Y或R或B键,窗口就会自动显示某种颜色,运行结果如下:

测试程序4:

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

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

代码如下:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
package mouse;
 
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 = 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)
   {
      var 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 == nullreturn;
      if (s == current) current = null;
      squares.remove(s);
      repaint();
   }
 
   private class MouseHandler extends MouseAdapter
   {
      public void mousePressed(MouseEvent event)
      {
         // 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)
      {
          //如果光标所在位置在正方形集合中包含并且鼠标点击次数>=2,则删除此位置的正方形
         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();
            int y = event.getY();
 
         // 拖动当前矩形使其居中(x,y)
            current.setFrame(x - SIDELENGTH / 2, y - SIDELENGTH / 2, SIDELENGTH, SIDELENGTH);
            repaint();
         }
      }
   }  
}

  

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
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();
   }
}

  

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
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);
      });
   }
}

  运行结果如下:

学习总结:

通过本周的学习,我知道了如何进行事件处理,

测试程序4:

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

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

代码如下:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
package mouse;
 
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 = 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)
   {
      var 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 == nullreturn;
      if (s == current) current = null;
      squares.remove(s);
      repaint();
   }
 
   private class MouseHandler extends MouseAdapter
   {
      public void mousePressed(MouseEvent event)
      {
         // 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)
      {
          //如果光标所在位置在正方形集合中包含并且鼠标点击次数>=2,则删除此位置的正方形
         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();
            int y = event.getY();
 
         // 拖动当前矩形使其居中(x,y)
            current.setFrame(x - SIDELENGTH / 2, y - SIDELENGTH / 2, SIDELENGTH, SIDELENGTH);
            repaint();
         }
      }
   }  
}

  

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
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();
   }
}

  

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
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);
      });
   }
}

  运行结果如下:

测试程序4:

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

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

代码如下:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
package mouse;
 
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 = 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)
   {
      var 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 == nullreturn;
      if (s == current) current = null;
      squares.remove(s);
      repaint();
   }
 
   private class MouseHandler extends MouseAdapter
   {
      public void mousePressed(MouseEvent event)
      {
         // 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)
      {
          //如果光标所在位置在正方形集合中包含并且鼠标点击次数>=2,则删除此位置的正方形
         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();
            int y = event.getY();
 
         // 拖动当前矩形使其居中(x,y)
            current.setFrame(x - SIDELENGTH / 2, y - SIDELENGTH / 2, SIDELENGTH, SIDELENGTH);
            repaint();
         }
      }
   }  
}

  

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
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();
   }
}

  

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
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);
      });
   }
}

  运行结果如下:

测试程序4:

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

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

代码如下:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
package mouse;
 
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 = 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)
   {
      var 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 == nullreturn;
      if (s == current) current = null;
      squares.remove(s);
      repaint();
   }
 
   private class MouseHandler extends MouseAdapter
   {
      public void mousePressed(MouseEvent event)
      {
         // 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)
      {
          //如果光标所在位置在正方形集合中包含并且鼠标点击次数>=2,则删除此位置的正方形
         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();
            int y = event.getY();
 
         // 拖动当前矩形使其居中(x,y)
            current.setFrame(x - SIDELENGTH / 2, y - SIDELENGTH / 2, SIDELENGTH, SIDELENGTH);
            repaint();
         }
      }
   }  
}

  运行结果如下:

学习总结:

通过本次实验

测试程序4:

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

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

代码如下:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
package mouse;
 
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 = 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)
   {
      var 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 == nullreturn;
      if (s == current) current = null;
      squares.remove(s);
      repaint();
   }
 
   private class MouseHandler extends MouseAdapter
   {
      public void mousePressed(MouseEvent event)
      {
         // 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)
      {
          //如果光标所在位置在正方形集合中包含并且鼠标点击次数>=2,则删除此位置的正方形
         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();
            int y = event.getY();
 
         // 拖动当前矩形使其居中(x,y)
            current.setFrame(x - SIDELENGTH / 2, y - SIDELENGTH / 2, SIDELENGTH, SIDELENGTH);
            repaint();
         }
      }
   }  
}

  

 

 

  运行结果如下:

学习总结:

通过本次实验,熟悉掌握了Java的异常机制,通过new一个数组,从而通过数组的下标取出内容,当下标不合法时就会出现数组下标越界异常,通过catch铺获异常,并对异常做出处理。这仅仅是对简单异常的处理,还须更进一步对异常熟悉,还要对字符串的练习和掌握。通过实验课上学长演示实验,再用lambda表达式以及匿名类等简化程序,希望以后在学长的帮助下能学的更好。

原文地址:https://www.cnblogs.com/zyq559208/p/11930842.html