201771010110孔维滢《面向对象程序设计(java)》第十三周学习总结(代码片段)

weiron weiron     2023-01-24     152

关键词:

理论知识部分

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

                    监听器接口方法实现

                                class Mylistener implements ActionListener   public void actionPerformed (ActionEvent event)   ……

2.用匿名类、lambda表达式简化程序:

    例ButtonTest.java中,各按钮需要同样的处理:

                a.使用字符串构造按钮对象;

                b.把按钮添加到面板上;

                c.用对应的颜色构造一个动作监听器;

                d.注册动作监听器。

3.适配器类:

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

    捕获窗口事件的监听器:

             WindowListener listener=…..; frame.addWindowListener(listener);

    注册事件监听器:

              可将一个Terminator对象注册为事件监听器:

                              WindowListener listener=new Terminator();

                              frame.addWindowListener(listener);

4.动作事件:

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

    动作对象是一个封装下列内容的对象:

                           –命令的说明:一个文本字符串和一个可选图标;

                           –执行命令所需要的参数。

5.鼠标事件:

    鼠标事件 – MouseEvent

    鼠标监听器接口

                              – MouseListener

                              – MouseMotionListener

    鼠标监听器适配器

                              – MouseAdapter

                              – MouseMotionAdapter

实验部分:

    实验1:

测试程序1:

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();//构建一个ButtonFrame类对象
         frame.setTitle("ButtonTest");//设置Title属性,确定框架标题栏中的文字
         frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);//设置默认关闭操作,退出并关闭
         frame.setVisible(true);//设置Visible属性,组件可见
      );
   

  

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);//调用add方法将按钮添加到面板
      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//实现了ActionListener的接口类
   
      private Color backgroundColor;

      public ColorAction(Color c)
      
         backgroundColor = c;
      

      public void actionPerformed(ActionEvent event)//actionListener方法接收一个ActionEvent对象参数
      
         buttonPanel.setBackground(backgroundColor);
      
   

  输出结果:

技术分享图片

测试程序2:

package plaf;

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();//构建一个PlafFrame类对象
         frame.setTitle("PlafTest");//设置Title属性,确定框架标题栏中的文字
         frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);//设置默认关闭操作,退出并关闭
         frame.setVisible(true);//设置Visible属性,组件可见
      );
   

  

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();//获得一个用于描述已安装的观感实现的对象数组
      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();
         
      );
   //使用辅助方法makeButton和匿名内部类指定按钮动作

 输出结果:

技术分享图片

测试程序3:

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();//构建一个ActionFrame类对象
         frame.setTitle("ActionTest");//设置Title属性,确定框架标题栏中的文字
         frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);//设置默认关闭操作,退出并关闭
         frame.setVisible(true);//设置Visible属性,组件可见
      );
   

  

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

  输出结果:

技术分享图片

测试程序4:

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();//构建一个MouseFrame类对象
         frame.setTitle("MouseTest");//设置Title属性,确定框架标题栏中的文字
         frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);//设置默认关闭操作,退出并关闭
         frame.setVisible(true);//设置Visible属性,组件可见
      );
   

 

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

 输出结果:

技术分享图片

实验2:结对编程练习

结对编程伙伴:冯志霞

import java.util.*;
import java.awt.*;
import javax.swing.*;
import java.awt.event.*;
import java.awt.Frame;
import java.io.File;
import java.io.FileNotFoundException;

public class Dianmingqi extends JFrame implements ActionListener 
	private JButton but;

	private JButton show;
	private static boolean flag = true;

	public static void main(String arguments[]) 
		new Dianmingqi();

	

	public Dianmingqi() 

		but = new JButton("START");
		but.setBounds(100, 150, 100, 40);

		show = new JButton("开始点名");
		show.setBounds(80, 80, 180, 30);
		show.setFont(new Font("宋体", Font.BOLD, 30));

		add(but);

		add(show);

		setLayout(null);// 布局管理器必须先初始化为空才能赋值
		setVisible(true);
		setResizable(false);
		setBounds(100, 100, 300, 300);
        //setBackground(Color.red);不起作用
		this.getContentPane().setBackground(Color.cyan);
		setTitle("START");
		setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

		but.addActionListener(this);
	

	public void actionPerformed(ActionEvent e) 
		int i = 0;
		String names[] = new String[50];
		try 
			Scanner in = new Scanner(new File("studentnamelist.txt"));
			while (in.hasNextLine()) 
				names[i] = in.nextLine();
				i++;
			
		 catch (FileNotFoundException e1) 

			e1.printStackTrace();
		

		if (but.getText() == "START") 

			show.setBackground(Color.BLUE);
			flag = true;
			new Thread() 
				public void run() 
					while (Dianmingqi.flag) 
						Random r = new Random();
						int i = r.nextInt(47);
						show.setText(names[i]);
					
				
			.start();
			but.setText("STOP");// 更改文本内容
			but.setBackground(Color.YELLOW);
		 else if (but.getText() == "STOP") 
			flag = false;
			but.setText("START");
			but.setBackground(Color.WHITE);
			show.setBackground(Color.GREEN);
		
	

  技术分享图片

实验总结:

这个周的结对编程练习,由于对很多知识的不理解,无法完全实现编程题的内容,我深感自己的不足。对于代码中的一些方法还不是能够完全理解。

package 点名器;

import java.io.*;
import java.awt.*;
import java.awt.event.*;
import java.util.List;

import javax.swing.JFrame;

import java.util.ArrayList;

public class RollCaller extends JFrame
    
    private String fileName="studentnamelist.txt";
    private File f;
    private FileReader fr;
    private BufferedReader br;
    private List<String> names=new ArrayList<String>();
    private String Name;
    private Label labelName;
    private Button button;
    
    public static void main(String[] args)
    
        RollCaller rollcaller=new RollCaller();
        rollcaller.newFrame();
        rollcaller.read();
    
    
    public void newFrame()
    
        labelName=new Label("随机点名");
        button=new Button("START");
        
        this.setLocation(300,300);
        this.setResizable(true);//设置此窗体是否可由用户调整大小。
        this.setSize(1000,800);
        this.add(labelName,BorderLayout.NORTH);
        this.add(button,BorderLayout.CENTER);
        this.pack();
        this.setVisible(true);
        setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        button.addActionListener(new ButtonAction());
    

    public void read()
    
        try
            f=new File(fileName);
            if(!f.exists())
                f.createNewFile();
            
            fr=new FileReader(f);
            br=new BufferedReader(fr);
            String str=br.readLine();
            while(str!=null)
                names.add(str);
                str=br.readLine();
            
        catch(Exception e)
            e.printStackTrace();
            
    
    
    public void name()
    
        try
            int index=(int)(Math.random()*names.size());
            Name=names.get(index);
            catch(Exception e)
                e.printStackTrace();
                
        
    
    private class ButtonAction implements ActionListener
    
        public void actionPerformed(ActionEvent e)
            name();
            labelName.setText(Name);
        
    

 这次的作业,我在网络中查询了很多,

 通过在网上查询,我查到了BufferedReader由Reader类扩展而来,提供文本读取。

 还有label对象是一个可在容器中放置文本的组件。一个标签只显示一行只读文本。文本可由应用程序更改,但是用户不能直接对其进行编辑。

 但是这个代码还存在着很多问题,对于很多知识我还需更多的掌握,不论是从程序的实用,还是外观,都还需更加深入的学习。

201771010110孔维滢《面向对象程序设计(java)》第十二周学习总结

理论知识部分1.Java的抽象窗口工具箱(AbstractWindowToolkit,AWT)包含在java.awt包中,它提供了许多用来设计GUI的组件类和容器类。2.Swing用户界面库是非基于对等体的GUI工具箱。Swing类库被放在javax.swing包里。3.大部分AWT组件都有其Swing... 查看详情

201771010110孔维滢《面向对象程序设计(java)》第二周学习总结(代码片段)

理论知识内容: 1.标识符:  标识符由字母、下划线、美元符号和数字组成,且第一个符号不能为数字。  合法标识符:Hello、$1234、程序名、www_123  标识符可用作:类名、变量名、方法名、数组名、文... 查看详情

201771010110孔维滢面向对象程序设计(java)第7周学习指导及要求

学习目标深入理解OO程序设计的特征:继承、多态;熟练掌握Java语言中基于类、继承技术构造程序的语法知识;利用继承定义类设计程序,能够设计开发含有1个主类、2个以上用户自定义类的应用程序。实验部分:1.实验目的与... 查看详情

孔维滢20171010110《面向对象程序设计(java)》第九周学习总结(代码片段)

实验九1、实验目的与要求(1)掌握java异常处理技术;(2)了解断言的用法;(3)了解日志的用途;(4)掌握程序基础调试技巧;2、实验内容和步骤实验1:package异常;//异常示例1publicclassExceptionDemo1publicstaticvoidmain(Stringargs[])inta=0;if(a==0)Syst... 查看详情

孔维滢20171010110《面向对象程序设计(java)》第十五周学习总结

实验十五 GUI编程练习与应用程序部署1、实验目的与要求(1)掌握Java应用程序的打包操作;(2)了解应用程序存储配置信息的两种方法;(3)掌握基于JNLP协议的javaWebStart应用程序的发布方法;(5)掌握JavaGUI编程技术。2、实验内容和... 查看详情

孔维滢20171010110《面向对象程序设计(java)》第十周学习总结

理论知识:         1.泛型类的定义,一个泛型类就是具有一个或多个类型变量的类,即创建用类型作为参数的类。如:classGenerics<K,V>;      2.泛型方法,除了泛型类外,... 查看详情

孔维滢20171010110《面向对象程序设计(java)》第十七周学习总结

理论知识部分:1.程序与进程:   程序是一段静态的代码,它是应用程序执行的蓝本。   进程是程序的一次动态执行,它对应了从代码加载、执行至执行完毕的一个完整过程。2.多线程   多线程... 查看详情

面向对象程序设计介绍以及面向对象的基本特征

  面向对象的程序设计(ObjectOrientedProgramming,OOP)方法是目前比较流行的程序设计方法,和面向过程的程序设计比,它更符合人类的自然思维方式。在面向过程程序设计中,程序=数据+算法,数据和对数据的操作是分离的,如... 查看详情

《面向对象程序设计概述》牛咏梅

面向对象程序设计概述牛咏梅(南阳理工学院河南南阳473000)摘要:分析传统程序设计方法与面向对象程序设计方法之间的差别,重点分析了面向对象程序设计方法的特点,介绍了面向对象程序设计方法的步骤及其优点。关键词:面向对... 查看详情

java面向对象大致梳理

...概述:Java设计语言面向对象:Java语言是一种面向对象的程序设计语言,而面向对象思想是一种程序设计思想,我们在面向对象思想的指引下,使用Java语言去设计、开发计算机程序。这里的对象泛指现实中一切事物,每种事物都... 查看详情

面向对象的程序设计

阅读目录一面向对象的程序设计的由来二什么是面向对象的程序设计及为什么要有它三类与对象四属性查找五绑定到对象的方法的特殊之处六对象之间的交互七练习八继承与派生九多态与多态性十封装十一绑定方法与非绑定方法... 查看详情

面向对象思想

...0年代,位于美国加州的Xerox研究中心推出smalltalk语言及其程序设计环境,使得面向对象程序设计方法得到比较完善的实现,掀起了面向对象研究的高潮。到80年代中后期,面向对象的软件设计和程序设计方法 查看详情

面向对象设计----软件设计师

上午12分下午两大答题30分面向对象的基本概念❤❤❤❤❤采用面向对象的软件开发,通常由面向对象分析,面向对象设计,面向对象实现1面向对象分析OOA:获取对应用问题的理解,主要任务是抽取和整理用户需求并建立问题域精确模... 查看详情

面向对象分析与设计面向对象设计包括哪些内容

一、总述面向对象分析的输入是用户的功能需求,输出是简单的、理性化的分析模型,此阶段的工作更多侧重于如何理解软件的功能需求;面向对象设计的输入是面向对象分析的结果,蔬菜水果最终的、细化后的设计模型,此阶... 查看详情

面向对象思想初识

面向对象思想概述Java语言是一种面向对象的程序设计语言,而面向对象思想是一种程序设计思想,我们在面向对象思想的指引下,使用Java语言去设计、开发计算机程序。这里的对象泛指现实中一切事物,每种事物都具备自己的... 查看详情

面向过程程序设计,面向对象程序设计,可视化程序设计的异同

...开-闭原则。也使代码更易阅读。相对而言,面向过程的程序设计是面向对象程序设计的基础。面向对象的程序里面一定会有面向过程的程序片断的!可视化程序设计主要是一种技术 参考技术B这些是阶梯型向上发展的,一个比一... 查看详情

面向对象程序设计的总结

    自学习面向对象程序设计语言以来,深深体会到这种语言的魅力。与面向过程设计语言相比,随着学习的深入,两者的风格不一更加凸显。面向过程程序设计语言,典型的有C语言、C++,面向过程是一种以过程... 查看详情

面向对象的程序设计(代码片段)

一、什么是面向对象  面向对象编程是一种编程方式,使用“类”和“对象”来实现,所以,面向对象编程就是对“类”和“对象”的使用。  面向对象编程核心就是“对象”二字,“对象”是特征与技能的结合体。“类”... 查看详情