【138天】尚學堂高淇Java300集視頻精華筆記(84)

第84集:太陽系模型/基本類的封裝/Star類的創建

本集知識點

  1. 將對象儘量的抽象,能夠有效減小代碼量,好比此例中的Star類java

    package com.test084_087_solar;
    
    import java.awt.Graphics;
    import java.awt.Image;
    
    import com.test084_087_util.GameUtil;
    
    public class Star {
        Image img;
        double x,y;
        
        public void draw(Graphics g){
            g.drawImage(img,(int)x,(int)y,null);
        }
        
        public Star(Image img,double x,double y){
            this.img = img;
            this.x = x;
            this.y = y;
        }
        
        public Star(String imgpath,double x,double y){
            this.img = GameUtil.getImage(imgpath);
            this.x = x;
            this.y = y;
        }
        
    }
  2. 構建常量類的好處相似CSS,改一個地方,其它地方都改了,例如此例中的Constant.GAME_WIDTH。this

    package com.test084_087_util;
    
    /**
     * @author wangtao
     *    遊戲項目中用到的常量
     */
    public class Constant {
        public static final int GAME_WIDTH = 800;
        public static final int GAME_HEIGHT = 600;
        
    }
  3. paint會在對象加載時自動調用。code

    package com.test084_087_solar;
        
        import java.awt.Graphics;
        import java.awt.Image;
        
        import com.test084_087_util.Constant;
        import com.test084_087_util.GameUtil;
        import com.test084_087_util.MyFrame;
        
        public class SolarFrame extends MyFrame {
            Image bg = GameUtil.getImage("images/bg.jpg");
            Star sun = new Star("images/sun.jpg",Constant.GAME_WIDTH/2,Constant.GAME_HEIGHT/2);
            
            
            public void paint(Graphics g){
                g.drawImage(bg,0,0,null);
                sun.draw(g);
            }
            
            public static void main(String[] args){
                 new SolarFrame().launchFrame();
            }
        }
相關文章
相關標籤/搜索