图形叠加jlabel图标图标

时间:2015-06-15 11:00:53

标签: java swing graphics jlabel imageicon

我正在用java做游戏,我的问题是设置背景。 我尝试过使用g.drawImage(),但每次重绘都会导致fps下降很多。所以我通过使用JLabelImageIcon设置背景来修复此fps问题。但标签覆盖了图形,我该如何解决这个问题?

public class GameScreen extends Screen implements Observer {

private static GameScreen gamescreen;
private Game game;
private JLabel label = new JLabel();
private ImageIcon icon = new ImageIcon("./res/img/bg1.png");

private GameScreen() {
    setGame(Game.getInstance());

    setLayout(null);
    label.setIcon(icon);
    label.setBounds(0, 0, 600, 600);

    add(label);
}

public static GameScreen getInstance() {
    if(getGameScreen() == null) {
        setGameScreen(new GameScreen());
    }
    return getGameScreen();
}

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

    //PaintWorld
    new DrawableWorld().draw(g, getWidth(), getHeight());
    //Paint players
    new DrawablePlayer().draw(g, getWidth(), getHeight(), getGame().getPlayers());
    //Paint hud
    new DrawableHud().draw(g, getWidth(), getGame().getPlayers());
}

@Override
public void update(Observable o, Object arg) {
    repaint();
}
//getters & setters..

实施例: Example

PS:所有DrawableClasses都扩展了扩展JPanel的屏幕

2 个答案:

答案 0 :(得分:1)

g.drawImage是一种非常快速(到一定程度)的操作。绘图时是否缩放图像?您是否使用“最高质量”渲染提示?

答案 1 :(得分:0)

关注@serg.nechaev

    public class GameScreen extends Screen implements Observer {

private static GameScreen gamescreen;
private Game game;
//New static vars
private static BufferedImage image;
private static Image img;
private static int w = 0;
private static int h = 0;

private GameScreen() {
    setGame(Game.getInstance());
    setImage();
}

public static GameScreen getInstance() {
    if(getGameScreen() == null) {
        setGameScreen(new GameScreen());
    }
    return getGameScreen();
}

public void paintComponent(Graphics g) {
    super.paintComponent(g);
    //Scaling once
    if(w != getWidth() || h != getHeight()) {
        img = getImage().getScaledInstance(getWidth(), getHeight(), Image.SCALE_SMOOTH);
        w = getWidth();
        h = getHeight();    
    }
    else{
        g.drawImage(getImg(), 0, 0, this);  
    }

    //PaintWorld
    new DrawableWorld().draw(g, getWidth(), getHeight());
    //Paint players
    new DrawablePlayer().draw(g, getWidth(), getHeight(), getGame().getPlayers());
    //Paint hud
    new DrawableHud().draw(g, getWidth(), getGame().getPlayers());
}

@Override
public void update(Observable o, Object arg) {
    repaint();
}
//getters & setters..
    public BufferedImage getImage() {
    return image;
}

public void setImage() {
    try {
        GameScreen.image = ImageIO.read(new File("./res/img/bg1.png"));
    } catch (IOException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }
}

public Image getImg() {
    return GameScreen.img;
}

结果很好的fps: enter image description here