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

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

    事件处理
    11.1事件处理基础
    11.2动作事件
    11.3鼠标事件
    11.4 AWT事件继承层次

    11.1事件处理基础
    1)事件源(eventsource):能够产生事件的组件对象都可以成为事件源,如文本框、按钮等。事件源能够注册监听器并向监听器发送事件对象。

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

    3)事件对象(event object) : Java将事件的相关信息封装在事件对象中,不同的事件源可以产生不同类别的事件。所有的事件对象都派生于

    java. util. EventObjec t类。

    AWT事件处理机制的概要:
    ●监听器对象:是一个实现了特定监听器接口(listener interface) 的类实例。

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

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

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

    事件源和监听器之间的关系:

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

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

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

    ●注册监听器方法
      eventSourceObject.addEventListener(eventl istenerObject)
    ●下面是注册监听器的一-个示例:
      ActionListener listener= ....;
      JButton button=new JButon("*Ok");
      button.addActionListener(listener);

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

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

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

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

    ●监听器接口中方法实现
      class Mylistener implements ActionListener

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

      }

    例子:

    private class ColorAction implements ActionListener
    {   public ColorAction(Colorc)   {     backgroundColor= C;   }
    public void actionPerformed(ActionEvent event)
    {   buttonPanel.setBackground(backgroundColor); }   private Color backgroundColor; }

    命令按钮Jbutton主要API ( 教材444页)
    1.创建按钮对象
    JButton类常用构造方法:
      (1) JButton(String text):创建一个 带文本的按钮。
      (2) JButton(lcon icon) :创建一个带图标的按钮。
      (3) JButton(String text, lcon icon) :创建一个带文本和图标的按钮。

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

    11.1.2用匿名类、lambda表达 式简化程序
    ●例ButtonTest. java中,各按钮需要同样的处理:
    1)使用字符串构造按钮对象;
    2)把按钮添加到面板上;
    3)用对应的颜色构造-一个动作监听器;
    4)注册动作监听器。

    ●设计一个方法用来构造按钮: 

    public void makeButton(String name , Color backgroundColor)
    {
      JButton button=new JButton(name);
      buttonPanel.add(button);
      ColorAction action=new ColorAction(backgroundColor);
      button.addActionListener(action);
    }

    But tonFrame构造器代码调整为:
      makeButton("yellow",Color.YELLOW);
      makeButton("blue",Color.BLUE);
      makeButton("red" ,Color.RED);

     ●进一步把ColorAct ion改为匿名类

    public void makeButton(String name , Color ackgroundColor)
    { 
      JButton button=new JButton(name);
      buttonPanel,add(button);
      button.addActionListener(new ActionListener()
      {
      public void actionPerformed(ActionEvent event)
      {
      buttonPanel.setBackground(backgroundColor);
      }
      });
    }
    

    ●进一步把ColorAction改为匿lambda表达式

    public void makeButton(String name , Color ackgroundColor)
    { 
      JButton button=new JButton(name);
      buttonPanel.add(button);
      button.addActionListener( (e)->{
      buttonPanel.setBackground(backgroundColor);
      });
    }
    

    11.1.3示例:改变观感的方法
    ●Swing程序默认使用Metal观感,采用两种方式改变观感。
      1)第一种:在Java安装的子目录jre/1ib下的文件swing. properties中,将属性swing. defaultlaf设置为所希望的观感类名。

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

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

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

    2)捕获窗口事件的监听器:
      WindowListener lite.e....;
      frame.addWindowListener(listener);
    3)窗口监听器必须是实现WindowListener接口的类的一个对象,WindowListener接口中有七个方法,它们的名字是自解释的。

    (1) WindowListener按口( 教材452页)
    public interface WindowListener
    {
      void windowOpened(WindowEvent e);
      vold windowClosing(WindowEvente);
      vold windowClosed(WindowEvent e);
      void windowlconlfied(WindowEvent e);
      vold windowDeiconified(WindowEvent e);
      void windowActivated(WindowEvente);
      vold windowDeactivated(WindowEvente);
    }

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

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

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

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

    class Terminator extends WindowAdapter

    {
      public void windowClosing(WindowEvente)
      {
        System.exit(0);
      }

    }

    (4)注册事件监听器
    ●可将一个Terminator对象注册为事件监听器:
      WindowListener listener=new Terminator();
      frame.addWindowListenerl(listener);
    ●只要框架产生一个窗口事件,该事件就会传递给监听器对象。

    ●创建扩展于WindowAdapter的监听器类是很好的改进,但还可以进一步将上面语句也可简化为:

      frame.addWindowListener(new Terminator();

    (5)用匿名类简化
    frame.addWindowListener(new WindowAdapter()

    {
      public void windowClosing(WindowEvente)
      {
      System.exit(0);

      }
    });

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

    ●在AWT事件模型中,可设置用不同方式下达命令(如:点击按钮、菜单选项、按下键盘),其操作动作都是一样的。

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

    2)动作对象是一个封装下列内容的对象:
      — 命令的说明:一个文本字符串和一个可选图标;
      — 执行命令所需要的参数。

    3)Action扩展于ActionListener接口, 包含下列方法(教材458页) :

      —— void aot ionPerformed (AotionlEvent event)
      —— vold setFnab led(bool ean b)
      —— void isBnabled()
      —— void put Value (String key, 0bject value)
      —— void retValue (String ker)
      —— void addPropertyChanglistener (ProperChargeListener listener)
      —— void removePropertyChangeListener (ProperChangeListener listener)

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

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

    在动作事件处理应用中,可以直接扩展AbstractAction类,并在扩展类中实现act ionPerformed方法。

    下面程序构造一个用于执行改变颜色命令的动作对象:

    public class ColorAction extends AbstractAction
    {
      publlc ColorAction(String name, Icon lcon, Color c)
      {
      putValue(Action.NAME, name);
      putValue(Action.SMALL ICON, icon);
      putValue(Action.SHORT_ DESCRIPTION, "Set panel color to" +name.toLowerCase());
      putValue("olor",c);
      }
      public void actionPerformed(ActionEvent event)
      {
      Color c = (Color) getValue("color");
      buttonPanelsetBackground(c);
          }
    }
    

    ●测试程序创建了三个ColorAction的对象, 如下所示:
    1. Action yellowAction = new ColorAction("Yellow", newImagelcon'"yellow-ball.gir), Color.YELlow);

    2 Action blueAction = new ColorAction(" Blue", new Imagelcon("blue-ballgiT"), Color.BLUE);

    3. Action redAction = new ColorActin("Red", new Imagelcon("red-bal.gir), Color.RED);

    ●将这个动作与一一个按钮关联起来,由于Jbutton有一一个用Action对象作为参数的构造器,代码如下:

    1. buttonPanel.add(new JButton/yellowActio));
    2. buttonPanel.add(new JButton(blueActio);
    3. buttonPanel.add(new JButton(redAction));

    11.2.2击键关联映射
    ●将一个动作对象添加到击键中,以便让用户敲击键盘命令来执行这个动作。

    ●将动作与击键关联起来,需生成KeyStroke类对象。
      KeyStroke ctrBKey = KeyStroke.getKeyStroke("Ctrl B");
    ●下面是将击键与动作对象关联起来的方式(桥梁:动作键对象描述字符串)

    InputMap imap =buttonPanelgetnputMap(JComponent.WHEN_ ANCESTOR _OF_FOCUSED_ COMPONENT);

    imap,put(KeyStroke. getKeyStroke("ctrl Y"), "panel-yellow");
    ActionMap amap = buttonPanel.getActionMap();
    amap.put("panel-yellow". yellowAction);

    11.3鼠标事件
    ●鼠标事件
      - MouseEvent
    ●鼠标监听器接口
      - MouseListener
      - MouseMotionListener
    ●鼠标监听器适配器
      - MouseAdapter
      - MouseMotionAdapter

    一鼠标点击监听器接口
    public interface MouseListener extends EventListener {
      public void mouseClicked(MouseEvent e);
      public void mousePressed(MouseEvent e);
      public void mouseReleased(MouseEvent e);
      public void mouseEntered(MouseEvent e);
      public void mouseExited(MouseEvent e);

    }
    -鼠标移动监听器接口
    public interface MouseMotionListener extends EventListener {
      public void mouseDragged(MouseEvent e);
      public void mouseMoved(MouseEvent e);
    }

    ●用户点击鼠标按钮时,会调用三个监听器方法:
      -鼠标第- -次被按下时调用mousePressed方法;
      -鼠标被释放时调用mouseReleased方法;
      -两个动作完成之后,调用mouseCl icked方法。
    ●鼠标在组件上移动时,会调用mouseMoved方法。
    ●如果鼠标在移动的时候还按下了鼠标,则会调用mouseDragged方法。

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

    ●MouseEvent类中的重要方法
      - public int getX( ); .
      - public int getY( );
      - public Point getPoint( );
      - public int getClickCount( );

    设置光标
      - java.awt.Component;
      public void setCursor(Cursor C);
      -java.awt.Cursor;

      public static Cursor getDefaultCursor( );
      public static Cursor getPredefinedCursor(int type);

    11.4AWT事件继承层次
    ●所有的事件都是由java. util包中的EventObject类扩展而来。

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

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

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

    11.4.1 AWT中的事件分类
    ●AWT将事件分为低级(low-level)事件和语义(semantic)事件。

      一 语义事件:表达用户动作的事件。
        例:点击按钮(ActionEvent)。
      — 低级事件:形成语义事件的事件。
        例:点击按钮,包含了按下鼠标、连续移动鼠标、抬起鼠标事件。

    (1)语义事件
    AWT事件中常用的语义事件:
    ■ActionEvent (对应按钮点击、菜单选择、选择列表项或在文本域中键入ENTER) ;

    ■AdjustmentEvent (用户调节滚动条);
    ●ItemEvent (用户从复选框或列表项中选择一项) 。

    (2)低层事件
    AWT事件中常用的5个低级事件类:
    ■KeyEvent(- 一个键被按下或释放) ;
    MouseEvent(鼠标被按下、释放、移动或拖动);
    ■MouseWheelEvent (鼠标滚轮被转动);
    ■FocusEvent (某个组件获得或失去焦点);
    ■WindowEvent (窗口状态改变)。

    第二部分:实验部分

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

    测试程序1:

    elipse IDE中调试运行教材443-444页程序11-1,结合程序运行结果理解程序;

    在事件处理相关代码处添加注释;

    lambda表达式简化程序;

    掌握JButton组件的基本API;

    掌握Java中事件处理的基本编程模型。

    程序11-1

    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;//buttonPanel内容窗格对象
       private static final int DEFAULT_WIDTH = 300;
       private static final int DEFAULT_HEIGHT = 200;
    
       public ButtonFrame()
       {      
          setSize(DEFAULT_WIDTH, DEFAULT_HEIGHT);//用于显示窗口大小
    
          // 创建按钮(通过在按钮构造器中指定一个标签字符串,一个图标或两项都指定来创建一个按钮)
          var yellowButton = new JButton("Yellow");
          var blueButton = new JButton("Blue");
          var redButton = new JButton("Red");
    
          buttonPanel = new JPanel();
    
          // 调用add方法 添加按钮面板
          buttonPanel.add(yellowButton);
          buttonPanel.add(blueButton);
          buttonPanel.add(redButton);
    
          // 面板添加到框架
          add(buttonPanel);
    
          // 创建按钮操作,生成监听器对象
          var yellowAction = new ColorAction(Color.YELLOW);
          var blueAction = new ColorAction(Color.BLUE);
          var 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
       {
          private Color backgroundColor;
    
          public ColorAction(Color c)
          {
             backgroundColor = c;
          }
        //实现ActionListener接口
          public void actionPerformed(ActionEvent event)	//调用actionPerformed方法,接收一个ActionEvent对象参数
          {
             buttonPanel.setBackground(backgroundColor);
          }
       }
    }
    
    package button;
    
    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(() -> {
             var frame = new ButtonFrame();
             frame.setTitle("ButtonTest");
             frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
             frame.setVisible(true);
          });
       }
    }
    

    运行:

     用lambda表达式简化程序

    package button;
    
    import java.awt.*;
    import java.awt.event.*;
    import javax.swing.*;
    
    /**
     * A frame with a button panel.
     */
    public class test extends JFrame
    {
       private JPanel buttonPanel;
       private static final int DEFAULT_WIDTH = 300;
       private static final int DEFAULT_HEIGHT = 200;
    
       public test()
       {    
          setSize(DEFAULT_WIDTH, DEFAULT_HEIGHT);
          //创建一个面板对象
          buttonPanel = new JPanel();
          
          //连续调用三次makeButton方法
          makeButton("yellow",Color.YELLOW);
          makeButton("blue",Color.BLUE);
          makeButton("red",Color.RED);
          //将面板添加至框架中
          add(buttonPanel);
    
       }
       
      
       public void makeButton(String name,Color backgroundColor)
       {
    	   JButton button=new JButton(name);
    	   buttonPanel.add(button);
    	   button.addActionListener(event->
    	       buttonPanel.setBackground(backgroundColor));
       }
    }

    测试程序2

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

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

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

    程序11-2

    package plaf;
    
    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();
    		}
    		//使用makeButton辅助方法和匿名内部类指定按钮动作,即切换观感
    		private void makeButton(String name, String className) {
    			// TODO Auto-generated method stub
    			//将按钮添加到面板 
    			JButton button = new JButton(name);
    			buttonPanel.add(button);
    			//设置按钮动作 
    			button.addActionListener(event -> {
    				//按钮动作:切换到新的观感
    				try
    				{
    					UIManager.setLookAndFeel(className);	//调用静态UIManager.setLookAndFeel方法并提供所想要的观感名字
    					SwingUtilities.updateComponentTreeUI(this);//调用静态方法SwingUtilities.updateComponentTreeUI来刷新全部的组件集
    					pack();
    				}
    				catch (Exception e)
    				{
    					e.printStackTrace();
    				}
    			});
    			
    		}
    		
    }
    
    package plaf;
    
    import java.awt.EventQueue;
    
    import javax.swing.JFrame;
    
    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

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

    掌握AbstractAction类及其动作对象;

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

    程序11-3

    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();
    
          // 定义操作,设置图标
          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);
    
          // 为这些操作添加按钮到面板
          buttonPanel.add(new JButton(yellowAction));
          buttonPanel.add(new JButton(blueAction));
          buttonPanel.add(new JButton(redAction));
    
          // 面板添加到容器中
          add(buttonPanel);
    
          // 将Y、B和R键与名称关联 
          InputMap inputMap = buttonPanel.getInputMap(JComponent.WHEN_ANCESTOR_OF_FOCUSED_COMPONENT);
        //使用getInputMap方法从组件中得到输入映射(这个组件包含了拥有键盘焦点的组件)
          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类实现将对象映射到动作上的第2个映射
          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
           */
    	   //ColorAction类
          public ColorAction(String name, Icon icon, Color c)
          {
        	  //putValue方法存储和检索动作对象中的任意名/值。Action接口来实现
             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)//调用actionPerformed方法执行改变颜色的动作
          {
             var color = (Color) getValue("color");
             buttonPanel.setBackground(color);
          }
       }
    }
    
    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(() -> {
             var frame = new ActionFrame();
             frame.setTitle("ActionTest");
             frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
             frame.setVisible(true);
          });
       }
    }
    

    运行:

    测试程序4

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

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

    程序11-4、11-5

    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)
       {
          var g2 = (Graphics2D) g;
    
          // draw all squares
          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)// mousePressed方法(当鼠标点击所在小方块的像素之外时,就会绘制一个新的小方块)
          {
             // 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)// mouseClicked方法(双击鼠标,将小方块擦除)
          {
             // 如果双击,则删除当前正方形 
             current = find(event.getPoint());
             if (current != null && event.getClickCount() >= 2) remove(current);
          }
       }
    
       private class MouseMotionHandler implements MouseMotionListener
       {
          public void mouseMoved(MouseEvent event)//mouseMoved方法
          {
             // 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();//返回事件相对于源组件的水平 x 坐标
                int y = event.getY();//返回事件相对于源组件的垂直 y 坐标。
    
                // drag the current rectangle to center it at (x, y)
                current.setFrame(x - SIDELENGTH / 2, y - SIDELENGTH / 2, SIDELENGTH, SIDELENGTH);
              //将此 Rectangle2D 外部边界的位置和大小设置为指定矩形值。
                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.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);
          });
       }
    }
    

     

    运行:

    实验2:结对编程练习

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

    结对编程:吴丽丽

    主要思路:

     

     代码:

    package ID;
    
    import java.awt.Color;
    import java.awt.Font;
    import java.awt.event.ActionEvent;
    import java.awt.event.ActionListener;
    import java.io.File;
    import java.io.FileNotFoundException;
    import java.util.Random;
    import java.util.Scanner;
    
    import javax.swing.JButton;
    import javax.swing.JFrame;
    import javax.swing.JLabel;
    
    public class NameFrame extends JFrame implements ActionListener {
    	private JLabel jla;
        private JLabel jlb;
        private JButton jba;	//push按钮的实现
        private static boolean flag = true;	//开始的按钮是否点过
    	public NameFrame() {
    		this.setLayout(null);
    		//条件按钮
    	        jla = new JLabel("姓名");
    	        jlb = new JLabel("准备");
    	        jba = new JButton("开始");
    	        this.add(jla);//添加组件
    	        this.add(jlb);
    	        jla.setFont(new Font("Courier",Font.PLAIN,22));//设置字体
    	        jla.setHorizontalAlignment(JLabel.CENTER);//x轴对称
    	         jla.setVerticalAlignment(JLabel.CENTER);  //y轴对称      
    	         jla.setBounds(20,100,180,30);
    	         jlb.setOpaque(true);//设置控件不透明
    	         jlb.setBackground(Color.blue);//设置背景颜色
    	         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);
    	         //设置窗口大小
    	         jba.addActionListener(this);//监听器
    
    	         this.setTitle("随机点名器");//窗口标题
    	        this.setBounds(400,400,400,300);
    	        this.setVisible(true);//设置为可见性
    	        this.setDefaultCloseOperation(DISPOSE_ON_CLOSE);
    	    }
    	    public void actionPerformed(ActionEvent e){
    	        int i=0;
    	        String names[]=new String[50];
    	        try {
    	            Scanner in=new Scanner(new File("F:\2019studentlist.txt"));
    	            while(in.hasNextLine())//hasNextLine()用来检测下一行有没有输入
    	            {
    	                names[i]=in.nextLine();//因为之前用hasNextLine(),所以这里需要用nextLine()
    	                i++;
    	            }
    	        } catch (FileNotFoundException e1) {
    	            // TODO Auto-generated catch block
    	            e1.printStackTrace();
    	        }
    	        if(jba.getText()=="开始"){//返回按钮
    	            jlb.setBackground(Color.MAGENTA);
    	            flag = true;
    	          //用new Thread()进行异步加载
    	            new Thread(){   
    	                public void run(){
    	                    while(NameFrame.flag){
    	                    Random r = new Random(); 
    	                    int i= r.nextInt(35);//返还该元素,并重新选择另一个元素
    	                    jlb.setText(names[i]);
    	                    }
    	                }
    	            }.start();//使该线程开始执行;Java 虚拟机调用该线程的 run 方法
    	            jba.setText("停止");
    	            jba.setBackground(Color.YELLOW);
    	        }    
    	        else if(jba.getText()=="停止"){
    	            flag = false;
    	            jba.setText("开始");//按钮标题
    	            jba.setBackground(Color.WHITE);//“开始”颜色
    	            jlb.setBackground(Color.blue);
    	        }
    	     }
    	    public static void main(String arguments []){ 
    	        new NameFrame();
    	    }
    	
    }
    

    运行:

     

     

     实验总结:

       通过这一周的学习,我初步了解了有关事件处理的基本知识,对AWT事件处理机制有了基本的认识学会了如何用程序编辑创建按钮。但在本周的实验中,我发现我对于本周的学习以及今后知识的预习还是不到位,通过本次实验发现自己在实际编写代码中思维不够灵活,通过查找资料和询问同学才有所收获,希望在今后的学习中可以得到这方面的提高。

  • 相关阅读:
    nyoj-68-三点顺序-计算几何
    zoj--1089--Lotto---DFS VS 暴力求解
    zoj----1090---The Circumference of the Circle---数学几何
    nyoj-阶乘0
    nyoj-回文字符串--动态规划
    nyoj-最长公共子序列---动态规划
    hdu-1285确定比赛名次---拓扑排序
    等式数量---hash算法
    学生学籍管理系统
    2020.2.9 解决Zabbix agent is not available&windows下安装zabbix-agent 主机部署监控
  • 原文地址:https://www.cnblogs.com/LZ-728672/p/11914130.html
Copyright © 2020-2023  润新知