在另一个上显示图像

时间:2016-01-07 11:27:14

标签: java swing jframe jpanel graphics2d

目前我遇到的问题是Robot.png正在替换我的gameboard.png的图像。我想这样做,以便机器人.png位于电路板的顶部,并能够将机器人移动到电路板上。

Board.Java

import java.awt.Dimension;
import java.awt.Graphics;
import java.awt.Image;
import javax.swing.ImageIcon;
import javax.swing.JPanel;

public class Board extends JPanel {

private Image gameboard;


public Board(){
    initBoard();
}

private void initBoard(){
    loadImage();

    int w = gameboard.getWidth(this);
    int h = gameboard.getHeight(this);
    setPreferredSize(new Dimension(w,h));

}

private void loadImage(){

    ImageIcon i = new ImageIcon("res/gameboard.png");
    gameboard = i.getImage();



}   

@Override
public void paintComponent(Graphics g){
    g.drawImage(gameboard,0,0,null);

}


}

Player.Java

import javax.swing.*;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.Image;
import javax.swing.ImageIcon;

public class Player extends JPanel {

public void paint(Graphics g){
    Graphics2D g2d = (Graphics2D)g;

    ImageIcon ic = new ImageIcon("res/Robot.png");
    Image image1 = ic.getImage();
    g2d.drawImage(image1, 100, 100, null);
}

}

GameGUI.Java

import javax.swing.JFrame;
public class GameGui extends JFrame {

public GameGui(){

    initGui();

}

public void initGui(){

    add(new Board());
    add(new Player());
    setTitle("11+ Game");
    pack();
    setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    setLocationRelativeTo(null);
    setSize(1240,620);
}

}

1 个答案:

答案 0 :(得分:0)

您不需要每次都重新加载机器人图像。您应该使用ImageIO加载它,并将其保存在成员变量中。

否则,没有图像覆盖整个背景图像的方法是在drawImage调用中使用height和width参数

ExpressionVisitor