201871010114- Li Yansong "object-oriented programming (java)" Week 16 learning summary

------------ ------------ restore content begins

project

content

This work belongs courses

https://www.cnblogs.com/nwnu-daizh/

Where this requirement in the job

https://www.cnblogs.com/nwnu-daizh/p/11435127.html

Job learning objectives

 

(1) master the Java application packaging operations;

(2) to grasp the concept of threads;

(3) master the two techniques threads created.

(4) study design of the application GUI.

Part I: summary of the intellectual content of textbooks 14.1-14.3

Part II: Experimental part

1 , experimental purposes and requirements

(1) master the Java application packaging operations;

(2) to grasp the concept of threads;

(3) master the two techniques threads created.

2 , experimental and step

Experiment 1:  introduction of Chapter 13 sample programs, test procedures and code comments.

Test Procedure 1

In elipse IDE commissioning textbook 585 page size of 13-1 , in conjunction with the results of running the program understanding;

The generated JAR file to a different directory further, the archive is run, the program is to confirm the resources, and not from the current directory is read from a JAR file.

be able to create JAR method file;

Experiment code:

package thread; 

Import in java.awt *. ;
 Import the java.io. * ;
 Import the java.net *. ;
 Import Classes in java.util *. ;
 Import in javax.swing *. ; 

/ ** 
 * @version 1.41 2015-06-12 
 * @author Cay Horstmann
  * / 
public  class ResourceTest 
{    
   public  static  void main (String [] args) 
   {   // set the image interface window 
      EventQueue.invokeLater (() -> { 
         the JFrame Frame = new new ResourceTestFrame();
         frame.setTitle("ResourceTest");
         frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
         frame.setVisible(true);
      });
   }
}

/**
 * A frame that loads image and text resources.
 */
class ResourceTestFrame extends JFrame
{
   private static final int DEFAULT_WIDTH = 300;
   private static final int DEFAULT_HEIGHT = 300;

   public ResourceTestFrame()
   {
      the setSize (DEFAULT_WIDTH, DEFAULT_HEIGHT); 
      the URL of aboutURL = getClass () getResource ( "about.gif");. // use about.gif image file creation icon 
      Image img = new new ImageIcon (aboutURL) .getImage (); 
      setIconImage (img) ; 

      JTextArea textArea = new new JTextArea (); // create a blank text box 
      InputStream Stream = getClass () getResourceAsStream ( "about.txt");. // read about.txt file 
      the try (Scanner in = new new Scanner (Stream, "UTF-. 8" )) 
      { 
         the while (in.hasNext ()) // determines whether the file read data line
            textArea.append (in.nextLine () + "\ n-" ); 
      } 
      the Add (the textArea); // add files read into the text box 
   } 
}

The results:

 

 

 Click:

 

 

 

Test Procedure 2:

l In elipse IDE Debuging ThreadTest, combined result of the program be appreciated program;

l grasp the concept of threads;

master by a method to implement threads of extension class Thread;

Use Runnable Interface renovation program, with master method Runnable interface to create threads.

class Lefthand extends Thread { 
   public void run()
   {
       for(int i=0;i<=5;i++)
       {  System.out.println("You are Students!");
           try{   sleep(500);   }
           catch(InterruptedException e)
           { System.out.println("Lefthand error.");}    
       } 
  } 
}
class Righthand extends Thread {
    public void run()
    {
         for(int i=0;i<=5;i++)
         {   System.out.println("I am a Teacher!");
             try{  sleep(300);  }
             catch(InterruptedException e)
             { System.out.println("Righthand error.");}
         }
    }
}
public class ThreadTest 
{
     static Lefthand left;
     static Righthand right;
     public static void main(String[] args)
     {     left=new Lefthand();
           right=new Righthand();
           left.start();
           right.start();
     }
}

After using the Runnable interface transformation program

package 线程;
//线程的接口Runnable
class Lefthand implements Runnable{
           @Override
           public void run()
           {
               for(int i=0;i<=5;i++)
               {  System.out.println("You are Students!");
                   try{   Thread.sleep(500);   }
                   catch(InterruptedException e)
                   { System.out.println("Lefthand error.");}    
               } 
          } 
        }
        class Righthand implements Runnable {
            public void run()
            {
                 for(int i=0;i<=5;i++)
                 {   System.out.println("I am a Teacher!");
                     try{  Thread.sleep(300);  }
                     catch(InterruptedException e)
                     { System.out.println("Righthand error.");}
                 }
            }
        }
        public class ThreadTest 
        {
             static Lefthand left;
             static Righthand right;
             public static void main(String[] args)
             {     left=new Lefthand();
                   right=new Righthand();
                 new Thread(left).start();
                 new Thread(right).start();
                 
             }
        }

operation result:

 

 

 

Test Procedure 3:

l 625 program debugging textbooks 14-1, 14-2 in Elipse environment , 14-3 , combined result of the program understand the program;

l 631 program debugging textbooks 14-4 in Elipse environment, combined result of the program understand the program;

l comparison of two programs, to understand the concept of threads and uses;

l mastered both techniques thread creation.

14-1

package 线程;

import java.awt.*;
import java.awt.event.*;
import javax.swing.*;

/**
 * Shows an animated bouncing ball.
 * @version 1.34 2015-06-21
 * @author Cay Horstmann
 */
public class Bounce
{
   public static void main(String[] args)
   {  
      EventQueue.invokeLater(() -> {
         JFrame frame = new BounceFrame();
         frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
         frame.setVisible(true);
      });//创建一个GUI界面
   }
}

/**
 * The frame with ball component and buttons.
 */
class BounceFrame extends JFrame
{
   private BallComponent comp;
   public static final int STEPS = 1000;
   public static final int DELAY = 3;

   /*构造包含用于显示弹跳球和启动和关闭按钮*/
   public BounceFrame()
   {
      setTitle("Bounce");
      comp = new BallComponent();
      add(comp, BorderLayout.CENTER);//设置组件在页面的布局为边框布局的中央
      JPanel buttonPanel = new JPanel();
      addButton(buttonPanel, "Start", event -> addBall());//添加按钮到按钮面板中,并为其添加事件监听器addBall方法
      addButton(buttonPanel, "Close", event -> System.exit(0));
      add(buttonPanel, BorderLayout.SOUTH);//
      pack();
   }

   /**
    * Adds a button to a container.
    * @param c the container
    * @param title the button title
    * @param listener the action listener for the button
    */
   public void addButton(Container c, String title, ActionListener listener)
   {
      JButton button = new JButton(title);
      c.add(button);
      button.addActionListener(listener);
   }

   /* 在面板中添加一个弹跳球,使其弹跳1000次。
    */
   public void addBall()
   {
      try
      {
         Ball ball = new Ball();
         comp.add(ball);

         for (int i = 1; i <= STEPS; i++)
         {
            ball.move(comp.getBounds());
            comp.paint(comp.getGraphics());
            Thread.sleep(DELAY);//调用线程当中的Thread.sleep方法。用于暂停当前的线程活动
         }
      }
      catch (InterruptedException e)
      {
      }
   }
}

14-2

package 线程;

import java.awt.geom.*;

/* 在长方形边缘上移动和反弹的球*/
public class Ball
{
   private static final int XSIZE = 15;
   private static final int YSIZE = 15;
   private double x = 0;
   private double y = 0;
   private double dx = 1;
   private double dy = 1;

   // 将球移动到下一个位置,如果球碰到其中一个边,则反转方向
   public void move(Rectangle2D bounds)
   {
      x += dx;
      y += dy;
      if (x < bounds.getMinX())
      {
         x = bounds.getMinX();
         dx = -dx;
      }
      if (x + XSIZE >= bounds.getMaxX())
      {
         x = bounds.getMaxX() - XSIZE;
         dx = -dx;
      }
      if (y < bounds.getMinY())
      {
         y = bounds.getMinY();
         dy = -dy;
      }
      if (y + YSIZE >= bounds.getMaxY())
      {
         y = bounds.getMaxY() - YSIZE;
         dy = -dy;
      }
   }

   //获取球在其当前位置的形状
   public Ellipse2D getShape()
   {
      return new Ellipse2D.Double(x, y, XSIZE, YSIZE);
   }
}

14-3

package 线程;

import java.awt.*;
import java.util.*;
import javax.swing.*;
public class BallComponent extends JPanel
{
   private static final int DEFAULT_WIDTH = 450;
   private static final int DEFAULT_HEIGHT = 350;

   private java.util.List<Ball> balls = new ArrayList<>();
   
  //在面板上添加一个球
   public void add(Ball b)
   {
      balls.add(b);
   }

   public void paintComponent(Graphics g)
   {
      super.paintComponent(g); // erase background
      Graphics2D g2 = (Graphics2D) g;
      for (Ball b : balls)
      {
         g2.fill(b.getShape());
      }
   }
   
   public Dimension getPreferredSize() { return new Dimension(DEFAULT_WIDTH, DEFAULT_HEIGHT); }
}

运行结果:

Guess you like

Origin www.cnblogs.com/liyansong0198/p/12040730.html