2015-12-09 55 views
1

无论图像大小有多小,每次加载背景图像时都会遇到此问题。我添加了一张尺寸为3.81kb的1010x600 png图片。我从秋千使用计时器,以重画这一点。只要添加并绘制bg.paintIcon方法,游戏就会减慢速度。添加背景图像时Java游戏速度变慢

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(); 
      } 
     } 
    } 
} 
+0

这个'bg'对象是什么类? – Gimby

+0

ImageIcon类。 –

+2

您每次调用'paintComponent()'时都会启动20个线程,这就像......什么?每秒60次?我正在读这个吗?这太过分了。编辑:好吧,实际上我并不清楚你开始线程的频率。我不知道'e'和'letalive'是什么。但是这里有一些线程发生了可疑的事情。 –

回答

4

您的paintComponent代码应该绘制。期。没有其他的。

下面是你的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()); 
    } 
} 

此代码属于您的控制器。

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(); 
      } 
     } 
    } 
+1

@JetMag请考虑[接受](http://meta.stackexchange.com/questions/5234/how-does-accepting-an-answer-work/5235#5235)这个答案,如果它解决了问题,所以用户(可能和你有类似的问题)会立即知道哪个是最有用的答案。 –