JPanel背景图像与动画

时间:2015-02-21 20:27:05

标签: java jpanel

我正在使用JPanel进行2D游戏,并希望设置前景中发生动画的背景。我知道如何设置背景图像,但它会超过动画的其他图像。有解决方案的建议吗?

公共类GameBoard扩展了JPanel {

public final int EARTH_ORBIT_RADIUS = 200;
public final int BOARD_WIDTH = 800;
public final int BOARD_HEIGHT = 600;
public final int INITIAL_EARTH_X = 700;
public final int INITIAL_EARTH_Y = 300;
public final int INITIAL_DELAY = 100;
public final int PERIOD_DELAY = 30;
public final int SUN_COORDINATE_X = 500;
public final int SUN_COORDINATE_Y = 300;
public final int INITIAL_ASTEROID_X = 500;
public final int INITIAL_ASTEROID_Y = 100;

public int earth_x, earth_y;
public int asteroid_x, asteroid_y;
public int t = 0;
public int[] earthcoordinates;
public int[] asteroidcoordinates;
Image earth;
Image sun;
Image asteroid;
Image background;

Timer timer;


GameBoard(){

    initGameBoard();

    loadImage();

    earth_x = INITIAL_EARTH_X;
    earth_y = INITIAL_EARTH_Y;

    asteroid_x = INITIAL_ASTEROID_X;
    asteroid_y = INITIAL_ASTEROID_Y;

    timer = new Timer();
    timer.scheduleAtFixedRate(new ScheduledTask(), INITIAL_DELAY, PERIOD_DELAY);
}

void initGameBoard(){
    //setBackground(Color.BLACK);
    BackgroundPanel panel = new BackgroundPanel(background, BackgroundPanel.ACTUAL, 1.0f, 0.5f);
    add(panel);
    setPreferredSize(new Dimension(BOARD_WIDTH, BOARD_HEIGHT));
    setDoubleBuffered(true);

}

void loadImage(){
    ImageIcon earth_image_icon = new ImageIcon("earth.png");
    earth = earth_image_icon.getImage();

    ImageIcon sun_image_icon = new ImageIcon("sun.png");
    sun = sun_image_icon.getImage();

    ImageIcon asteroid_image_icon = new ImageIcon("asteroid.png");
    asteroid = asteroid_image_icon.getImage();

    ImageIcon bg_image_icon = new ImageIcon("bg_pr.png");
    background = bg_image_icon.getImage();



}

public void paintComponent(Graphics g){
    super.paintComponent(g);

    drawEarth(g);
    drawSun(g);
    drawAsteroid(g); 
    drawBackground(g);
}

void drawEarth(Graphics g) {

    g.drawImage(earth, earth_x, earth_y, this);
    Toolkit.getDefaultToolkit().sync();
}

void drawSun(Graphics g) {
    g.drawImage(sun, SUN_COORDINATE_X, SUN_COORDINATE_Y, this);
    Toolkit.getDefaultToolkit().sync();
}

void drawAsteroid(Graphics g) {
    g.drawImage(asteroid, asteroid_x, asteroid_y, this);
    Toolkit.getDefaultToolkit().sync();
}

void drawBackground(Graphics g){
    g.drawImage(background, 0, 0, null );
}

public class ScheduledTask extends TimerTask{

    @Override
    public void run() {
        OrbitCalculation oe = new OrbitCalculation();
        earthcoordinates = oe.earthOrbitCalculation(t);
        earth_x = earthcoordinates[0];
        earth_y = earthcoordinates[1];

        OrbitCalculation oa = new OrbitCalculation();
        asteroidcoordinates = oa.asteroidOrbitCalculation(t);
        asteroid_x = asteroidcoordinates[0];
        asteroid_y = asteroidcoordinates[1];

        t = t + 1 ;
        repaint();
    }   
}

}

0 个答案:

没有答案