java线程游戏之背景图片的移动

package com.plane;

import java.awt.Graphics;
import java.awt.Image;

import javax.swing.ImageIcon;
import javax.swing.JFrame;
import javax.swing.JPanel;

public class PlaneMain extends JPanel{
    private Image background;
    private Plane pl;
    public static void main(String[] args) {
        new PlaneMain();
    }
    public PlaneMain(){
        
        background = new ImageIcon(this.getClass().getResource("background.jpg")).getImage();
        pl = new Plane(background,0,-100,this);
        initUI();
        
    }
    
    public void initUI(){
        JFrame jf = new JFrame();
        jf.setSize(1000, 900);
        jf.setDefaultCloseOperation(3);
        jf.setLocationRelativeTo(null);
        
        jf.add(this);
        jf.setVisible(true);
        pl.start();
        
    }
    //Plane pl = new Plane(background,0,0,this);
    public void paint(Graphics g){
        super.paint(g);
        g.drawImage(pl.background, pl.x, pl.y, 1000, 1000, this);
   
}
}
package com.plane;

import java.awt.Image;

import javax.swing.JPanel;

public class Plane extends Thread{
    public Image background;
    public int x=0;
    public int y=-60;
    public JPanel jp;
    public int movesp=2;
    public Plane(Image background,int x,int y,JPanel jp){
        this.background = background;
        System.out.println(this.background);
        this.x = x;
        this.y = y;
        this.jp = jp;
    }
    public void move(){
        y+=movesp;
        if (y==0){
            y=-100;
        }
    }
    public void run(){
        
        while(true){
            move();
            jp.repaint();
            try {
                Thread.sleep(100);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
    }
    }
}
原文地址:https://www.cnblogs.com/chang1203/p/5861697.html