达拉草201771010105《面向对象程序设计(java)》第十三周学习总结

达拉草201771010105《面向对象程序设计(java)》第十三周学习总结

第一部分:理论知识

事件处理基础:

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

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

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

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

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

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

能够触发动作事件的动作,主要包括: (1) 点击按钮 (2) 双击一个列表中的选项; (3) 选择菜单项; (4) 在文本框中输入回车。

 监听器接口的实现:

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

监听器接口方法实现 class Mylistener implements ActionListener { public void actionPerformed (ActionEvent event) { …… } }

命令按钮Jbutton主要API:

1.创建按钮对象 JButton类常用的一组构造方法: (1) JButton(String text):创建一个带文本的按钮。 (2) JButton(Icon icon) :创建一个带图标的按钮。 (3)JButton(String text, Icon icon) :创建一个带文本和图标 的按钮。 

2.按钮对象的常用方法 ① getLabel( ):返回按钮的标签字符串; ② setLabel(String s):设置按钮的标签为字符串s。

 

 

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

实验时间 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中事件处理的基本编程模型。

 1 package button;
 2 
 3 import java.awt.*;
 4 import java.awt.event.*;
 5 import javax.swing.*;
 6 
 7 /**
 8  * A frame with a button panel
 9  */
10 public class ButtonFrame extends JFrame
11 {
12    private JPanel buttonPanel;
13    private static final int DEFAULT_WIDTH = 300;
14    private static final int DEFAULT_HEIGHT = 200;
15 
16    public ButtonFrame()
17    {      
18       setSize(DEFAULT_WIDTH, DEFAULT_HEIGHT);
19 
20       // 创建按钮
21       JButton yellowButton = new JButton("Yellow");
22       JButton blueButton = new JButton("Blue");
23       JButton redButton = new JButton("Red");
24 
25       buttonPanel = new JPanel();
26 
27       // 向面板添加按钮
28       buttonPanel.add(yellowButton);
29       buttonPanel.add(blueButton);
30       buttonPanel.add(redButton);
31 
32       // 将面板添加到帧
33       add(buttonPanel);
34 
35       // 创建按钮动作
36       ColorAction yellowAction = new ColorAction(Color.YELLOW);
37       ColorAction blueAction = new ColorAction(Color.BLUE);
38       ColorAction redAction = new ColorAction(Color.RED);
39 
40       // 用按钮关联动作
41       yellowButton.addActionListener(yellowAction);
42       blueButton.addActionListener(blueAction);
43       redButton.addActionListener(redAction);
44    }//通过addActionListener关联监听器对象和组件
45 
46    /**
47     * An action listener that sets the panel's background color.
48     */
49    private class ColorAction implements ActionListener//implements实现了ActionListener监听器接口
50    {
51       private Color backgroundColor;
52 
53       public ColorAction(Color c)
54       {
55          backgroundColor = c;
56       }
57 
58       public void actionPerformed(ActionEvent event)//更改容器的背景色
59       {
60          buttonPanel.setBackground(backgroundColor);
61       }
62    }
63 }
 1 package button;
 2 
 3 import java.awt.*;
 4 import javax.swing.*;
 5 
 6 /**
 7  * @version 1.34 2015-06-12
 8  * @author Cay Horstmann
 9  */
10 public class ButtonTest
11 {
12    public static void main(String[] args)
13    {
14       EventQueue.invokeLater(() -> {
15          JFrame frame = new ButtonFrame();
16          frame.setTitle("ButtonTest");
17          frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
18          frame.setVisible(true);
19       });
20    }
21 }

程序运行结果如下:

    

测试程序2:

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

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

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

 1 package plaf;
 2 
 3 import javax.swing.JButton;
 4 import javax.swing.JFrame;
 5 import javax.swing.JPanel;
 6 import javax.swing.SwingUtilities;
 7 import javax.swing.UIManager;
 8 
 9 /**
10  * A frame with a button panel for changing look-and-feel
11  */
12 public class PlafFrame extends JFrame
13 {
14    private JPanel buttonPanel;
15 
16    public PlafFrame()
17    {
18       buttonPanel = new JPanel();
19 
20       UIManager.LookAndFeelInfo[] infos = UIManager.getInstalledLookAndFeels();//返回表示当前可用的 LookAndFeel 实现的 LookAndFeelInfo 数组
21       for (UIManager.LookAndFeelInfo info : infos)
22          makeButton(info.getName(), info.getClassName());
23 
24       add(buttonPanel);//将指定组件追加到此容器的尾部
25       pack();//调整此窗口的大小,以适合其子组件的首选大小和布局
26    }
27 
28    /**
29     * Makes a button to change the pluggable look-and-feel.
30     * @param name the button name
31     * @param className the name of the look-and-feel class
32     */
33    private void makeButton(String name, String className)
34    {
35       // 向面板添加按钮
36 
37       JButton button = new JButton(name);//创建一个带文本的按钮
38       buttonPanel.add(button);
39 
40       // 设置按钮动作
41 
42       button.addActionListener(event -> {
43          // 按钮动作:切换到新的外观和感觉
44          try
45          {
46             UIManager.setLookAndFeel(className);
47             SwingUtilities.updateComponentTreeUI(this);
48             pack();//调整此窗口的大小,以适合其子组件的首选大小和布局。
49          }
50          catch (Exception e)
51          {
52             e.printStackTrace();
53          }
54       });
55    }
56 }
 1 package plaf;
 2 
 3 import java.awt.*;
 4 import javax.swing.*;
 5 
 6 /**
 7  * @version 1.32 2015-06-12
 8  * @author Cay Horstmann
 9  */
10 public class PlafTest
11 {
12    public static void main(String[] args)
13    {
14       EventQueue.invokeLater(() -> {
15          JFrame frame = new PlafFrame();
16          frame.setTitle("PlafTest");//将此窗体的标题设置为指定的字符串。
17          frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
18          frame.setVisible(true);
19       });
20    }
21 }

程序运行结果如下:

              

             

 

测试程序3:

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

l  掌握AbstractAction类及其动作对象;

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

 

 1 package action;
 2 
 3 import java.awt.*;
 4 import java.awt.event.*;
 5 import javax.swing.*;
 6 
 7 /**
 8  * A frame with a panel that demonstrates color change actions.
 9  */
10 public class ActionFrame extends JFrame
11 {
12    private JPanel buttonPanel;
13    private static final int DEFAULT_WIDTH = 300;
14    private static final int DEFAULT_HEIGHT = 200;
15 
16    public ActionFrame()
17    {
18       setSize(DEFAULT_WIDTH, DEFAULT_HEIGHT);
19 
20       buttonPanel = new JPanel();
21 
22       // 定义行为
23       //根据指定的文件创建一个 ImageIcon
24       Action yellowAction = new ColorAction("Yellow", new ImageIcon("yellow-ball.gif"),
25             Color.YELLOW);
26       Action blueAction = new ColorAction("Blue", new ImageIcon("blue-ball.gif"), Color.BLUE);
27       Action redAction = new ColorAction("Red", new ImageIcon("red-ball.gif"), Color.RED);
28 
29       // 为这些操作添加按钮
30       buttonPanel.add(new JButton(yellowAction));
31       buttonPanel.add(new JButton(blueAction));
32       buttonPanel.add(new JButton(redAction));
33 
34       // 将面板添加到帧
35       add(buttonPanel);
36 
37       // 将Y、B和R键与名称关联
38       InputMap imap = buttonPanel.getInputMap(JComponent.WHEN_ANCESTOR_OF_FOCUSED_COMPONENT);
39       imap.put(KeyStroke.getKeyStroke("ctrl Y"), "panel.yellow");
40       imap.put(KeyStroke.getKeyStroke("ctrl B"), "panel.blue");
41       imap.put(KeyStroke.getKeyStroke("ctrl R"), "panel.red");
42 
43       // 把名字和动作联系起来
44       ActionMap amap = buttonPanel.getActionMap();
45       amap.put("panel.yellow", yellowAction);
46       amap.put("panel.blue", blueAction);
47       amap.put("panel.red", redAction);
48    }
49    
50    public class ColorAction extends AbstractAction
51    {
52       /**
53        * Constructs a color action.
54        * @param name the name to show on the button
55        * @param icon the icon to display on the button
56        * @param c the background color
57        */
58       public ColorAction(String name, Icon icon, Color c)
59       {
60          putValue(Action.NAME, name);
61          putValue(Action.SMALL_ICON, icon);
62          putValue(Action.SHORT_DESCRIPTION, "Set panel color to " + name.toLowerCase());
63          putValue("color", c);
64       }
65 
66       public void actionPerformed(ActionEvent event)
67       {
68          Color c = (Color) getValue("color");
69          buttonPanel.setBackground(c);//设置此组件的背景色
70       }
71    }
72 }
 1 package action;
 2 
 3 import java.awt.*;
 4 import javax.swing.*;
 5 
 6 /**
 7  * @version 1.34 2015-06-12
 8  * @author Cay Horstmann
 9  */
10 public class ActionTest
11 {
12    public static void main(String[] args)
13    {
14       EventQueue.invokeLater(() -> {
15          JFrame frame = new ActionFrame();
16          frame.setTitle("ActionTest");//将此窗体的标题设置为指定的字符串
17          frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
18          frame.setVisible(true);
19       });
20    }
21 }

程序运行结果如下:

        

测试程序4:

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

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

  1 package mouse;
  2 
  3 import java.awt.*;
  4 import java.awt.event.*;
  5 import java.awt.geom.*;
  6 import java.util.*;
  7 import javax.swing.*;
  8 
  9 /**
 10  * A component with mouse operations for adding and removing squares.
 11  */
 12 public class MouseComponent extends JComponent
 13 {
 14    private static final int DEFAULT_WIDTH = 300;
 15    private static final int DEFAULT_HEIGHT = 200;
 16 
 17    private static final int SIDELENGTH = 10;
 18    private ArrayList<Rectangle2D> squares;
 19    private Rectangle2D current; // 包含鼠标光标的正方形
 20 
 21    public MouseComponent()
 22    {
 23       squares = new ArrayList<>();
 24       current = null;
 25 
 26       addMouseListener(new MouseHandler());
 27       addMouseMotionListener(new MouseMotionHandler());
 28    }
 29 
 30    public Dimension getPreferredSize() { return new Dimension(DEFAULT_WIDTH, DEFAULT_HEIGHT); }   
 31    
 32    public void paintComponent(Graphics g)
 33    {
 34       Graphics2D g2 = (Graphics2D) g;
 35 
 36       // 绘制所有正方形
 37       for (Rectangle2D r : squares)
 38          g2.draw(r);
 39    }
 40 
 41    /**
 42     * Finds the first square containing a point.
 43     * @param p a point
 44     * @return the first square that contains p
 45     */
 46    public Rectangle2D find(Point2D p)
 47    {
 48       for (Rectangle2D r : squares)
 49       {
 50          if (r.contains(p)) return r;
 51       }
 52       return null;
 53    }
 54 
 55    /**
 56     * Adds a square to the collection.
 57     * @param p the center of the square
 58     */
 59    public void add(Point2D p)
 60    {
 61       double x = p.getX();
 62       double y = p.getY();
 63 
 64       current = new Rectangle2D.Double(x - SIDELENGTH / 2, y - SIDELENGTH / 2, SIDELENGTH,
 65             SIDELENGTH);
 66       squares.add(current);
 67       repaint();
 68    }
 69 
 70    /**
 71     * Removes a square from the collection.
 72     * @param s the square to remove
 73     */
 74    public void remove(Rectangle2D s)
 75    {
 76       if (s == null) return;
 77       if (s == current) current = null;
 78       squares.remove(s);
 79       repaint();
 80    }
 81 
 82    private class MouseHandler extends MouseAdapter
 83    {
 84       public void mousePressed(MouseEvent event)
 85       {
 86          // 如果光标不在正方形中,则添加一个新的正方形
 87          current = find(event.getPoint());
 88          if (current == null) add(event.getPoint());
 89       }
 90 
 91       public void mouseClicked(MouseEvent event)
 92       {
 93          // 如果双击,删除当前方块
 94          current = find(event.getPoint());
 95          if (current != null && event.getClickCount() >= 2) remove(current);
 96       }
 97    }
 98 
 99    private class MouseMotionHandler implements MouseMotionListener
100    {
101       public void mouseMoved(MouseEvent event)
102       {
103          // 设置鼠标光标,如果里面是交叉
104          // 一个矩形
105 
106          if (find(event.getPoint()) == null) setCursor(Cursor.getDefaultCursor());
107          else setCursor(Cursor.getPredefinedCursor(Cursor.CROSSHAIR_CURSOR));
108       }
109 
110       public void mouseDragged(MouseEvent event)
111       {
112          if (current != null)
113          {
114             int x = event.getX();
115             int y = event.getY();
116 
117             // 拖动当前矩形将其置于(x,y)中心
118             current.setFrame(x - SIDELENGTH / 2, y - SIDELENGTH / 2, SIDELENGTH, SIDELENGTH);
119             repaint();
120          }
121       }
122    }   
123 }
 1 package mouse;
 2 
 3 import javax.swing.*;
 4 
 5 /**
 6  * A frame containing a panel for testing mouse operations
 7  */
 8 public class MouseFrame extends JFrame
 9 {
10    public MouseFrame()
11    {
12       add(new MouseComponent());//将指定组件追加到此容器的尾部
13       pack();//调整此窗口的大小,以适合其子组件的首选大小和布局
14    }
15 }
 1 package mouse;
 2 
 3 import java.awt.*;
 4 import javax.swing.*;
 5 
 6 /**
 7  * @version 1.34 2015-06-12
 8  * @author Cay Horstmann
 9  */
10 public class MouseTest
11 {
12    public static void main(String[] args)
13    {
14       EventQueue.invokeLater(() -> {
15          JFrame frame = new MouseFrame();
16          frame.setTitle("MouseTest");//将此窗体的标题设置为指定的字符串
17          frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
18          frame.setVisible(true);
19       });
20    }
21 }

程序运行结果如下:

      

实验2:结对编程练习

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

结对同学:韩腊梅

 1 package 点名器;
 2 
 3 import java.util.*;
 4 import java.awt.*;
 5 import javax.swing.*;
 6 import java.awt.event.*;
 7 import java.io.File;
 8 import java.io.FileNotFoundException;
 9 
10 import javax.swing.event.*;
11 public class NameFrame extends JFrame implements ActionListener{
12    
13     private JButton A;
14     private JButton B;
15     private static boolean flag = true;
16     public NameFrame(){
17         this.setLayout(null);//布局管理器必须先初始化为空才能赋值
18         A = new JButton("准备中");
19         B = new JButton("开始");
20         this.add(A);
21          A.setOpaque(true);//如果为 true,则该组件绘制其边界内的所有像素。
22          A.setBackground(Color.CYAN);
23          A.setFont(new Font("Courier",Font.PLAIN,22));
24          A.setHorizontalAlignment(JButton.CENTER);
25          A.setVerticalAlignment(JButton.CENTER);        
26          A.setBounds(100,80,200,60);
27           
28          this.add(B);
29          B.setBounds(160,160,80,26);
30          B.addActionListener(this);
31 
32         this.setTitle("随机点名器");
33         this.setBounds(400,400,400,300);
34         this.setVisible(true);
35         this.setDefaultCloseOperation(DISPOSE_ON_CLOSE);
36     }
37     public void actionPerformed(ActionEvent e){
38         int i=0;
39         String names[]=new String[50];
40         try {
41             Scanner in=new Scanner(new File("D:\\studentnamelist.txt"));
42             while(in.hasNextLine())
43             {
44                 names[i]=in.nextLine();
45                 i++;
46             }
47         } catch (FileNotFoundException e1) {
48             // TODO Auto-generated catch block
49             e1.printStackTrace();
50         }
51         if(B.getText()=="开始"){
52             A.setBackground(Color.ORANGE);
53             flag = true;
54             new Thread(){   
55                 public void run(){
56                     while(NameFrame.flag){
57                     Random r = new Random(); 
58                     int i= r.nextInt(47);
59                     A.setText(names[i]);
60                     }
61                 }
62             }.start();
63             B.setText("停止");
64             B.setBackground(Color.YELLOW);
65         }    
66         else if(B.getText()=="停止"){
67             flag = false;
68             B.setText("开始");
69             B.setBackground(Color.BLUE);
70             A.setBackground(Color.WHITE);
71         }
72      }
73     public static void main(String arguments []){ 
74         new NameFrame();
75     }
76 }

运行结果如下:

实验总结:

       在这周的学习中我们学习了图形界面事件处理技术的知识,首先掌握了事件处理的基本原理,并学会了事件处理的基本编程模型。通过这次的实验基本上掌握了事件处理的基本原理,但对用lambda表达式简化程序不是很理解。

posted on 2018-11-25 16:52  DLC  阅读(215)  评论(0编辑  收藏  举报

导航