简体   繁体   English

添加背景图片时Java游戏速度变慢

[英]Java Game slows down when adding background images

I am having this problem whenever I load a background image no matter how small the size of the image. 每当加载背景图像时,无论图像大小有多小,我都会遇到此问题。 I am adding an image of 1010x600 png picture with a size of 3.81kb. 我正在添加大小为3.81kb的1010x600 png图片的图像。 I am using timer from swing in order to repaint this. 我正在使用Swing中的计时器来重绘此内容。 The game just slows down whenever I add and paint the bg.paintIcon method. 每当我添加和绘制bg.paintIcon方法时,游戏的速度就会降低。

public void paintComponent(Graphics g){
    super.paintComponent(g);
    bg.paintIcon(null, g, 0, 0);
    p.img.paintIcon(null, g, p.x, p.y);
    g2p = (Graphics2D)g;
    g2p.setColor(Color.green);
    g2p.fillRect(20, 10, (int)Math.ceil((p.health/1000.0)*960), 20);
    life.paintIcon(null, g, 0, 8);

    g2p.setColor(Color.black);
    g2p.drawRect(19, 34, 960+1, 20+1);
    g2p.setColor(Color.blue);
    g2p.fillRect(20, 35, (int)Math.ceil((p.mana/500.0)*960), 20);

    //System.out.println(df.format(p.health/1000.0));
    jl.setLocation(p.x, p.y);
    //jl.setText("Current Health: "+p.health);
    for (int i = 0 ; i < 20 ; i++){//IMPORTANT
        g2[i] = (Graphics2D) g;
        e[i].img.paintIcon(null, g, e[i].getx(), e[i].gety());
        if (e[i].dead){
            gen[i] = new Thread(new Generation(i));
            if (letalive){
                letalive = false;
                gen[i].start();
            }
        }
    }
}

Your paintComponent code should paint. 您的paintComponent代码应该绘制。 Period. 期。 Nothing else. 没有其他的。

Here's how your paintComponent method should look. 这是paintComponent方法的外观。

public void paintComponent(Graphics g){
    super.paintComponent(g);
    bg.paintIcon(null, g, 0, 0);
    p.img.paintIcon(null, g, p.x, p.y);
    g2p = (Graphics2D)g;
    g2p.setColor(Color.green);
    g2p.fillRect(20, 10, (int)Math.ceil((p.health/1000.0)*960), 20);
    life.paintIcon(null, g, 0, 8);

    g2p.setColor(Color.black);
    g2p.drawRect(19, 34, 960+1, 20+1);
    g2p.setColor(Color.blue);
    g2p.fillRect(20, 35, (int)Math.ceil((p.mana/500.0)*960), 20);

    //System.out.println(df.format(p.health/1000.0));
    jl.setLocation(p.x, p.y);
    //jl.setText("Current Health: "+p.health);
    for (int i = 0 ; i < 20 ; i++){//IMPORTANT
        e[i].img.paintIcon(null, g, e[i].getx(), e[i].gety());
    }
}

This code belongs in your controller. 此代码属于您的控制器。

   for (int i = 0 ; i < 20 ; i++) {
       if (e[i].dead){
            gen[i] = new Thread(new Generation(i));
            if (letalive){
                letalive = false;
                gen[i].start();
            }
        }
    }

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM