JPanel上paintComponent()的性能较差

时间:2019-06-18 04:53:58

标签: java performance jframe jpanel

我在此处发布的代码存在性能问题。 我是一名Java新手,并且尝试在JPanel上重新绘制图像,然后将其显示在JFrame上。经过大量的反复试验,代码终于可以工作了。问题在于它的性能非常低。正在重新绘制的图像似乎滞后。另外,当我在屏幕上移动JFrame时,它会滞后。我在OS Linux Mint上使用Eclipse。我不确定这是问题还是代码。 我将不胜感激!

谢谢, 西蒙

主类:

package pack1;

import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import javax.imageio.ImageIO;
import javax.swing.JFrame;
import javax.swing.JPanel;

public class Main extends JPanel {

/**
 * 
 */
private static final long serialVersionUID = -7460454277320732933L;
public static BufferedImage image;
public static int y = 0;
public static BufferedImage image2;
public static int y2 = -600;

public Main() {

    try {
     image = ImageIO.read(new File("spazio/stelle.png"));
     image2 = ImageIO.read(new File("spazio/stelle.png"));
    }
    catch (IOException e){
        e.printStackTrace();
        System.out.println("Quadro non esiste");
    }
}

@Override
public void paintComponent(Graphics g){
Graphics2D g2 = (Graphics2D) g;
g2.drawImage(image, 0, y, 800,600,null);
g2.drawImage(image2, 0, y2,800,600,null);
repaint();
}



public static void main(String[] args) {
    JFrame f = new JFrame("Spazio");
    f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    Main panel = new Main();
    panel.setBounds(0, 0, 800, 600);
    f.add(panel);
    f.setSize(image.getWidth(),image.getHeight());
    f.setVisible(true);
    new Background();
    }

}

课程背景:

package pack1;

import java.util.TimerTask;
import java.util.Timer;

public class Background {
 Timer back;
    public Background(){
    back = new Timer();
    back.scheduleAtFixedRate(new TimerTask (){

        @Override
 public void run(){
     if (Main.y<600) {
         Main.y+= 2;
     }
     if (Main.y2<600) {
         Main.y2+=2;
     }
     else if (Main.y>=600) Main.y = 0;
     else if (Main.y2>=600) Main.y2=-595; 
 }},0,80);





    }

}

1 个答案:

答案 0 :(得分:0)

MadProgrammer在他的评论中是正确的。您的第一个更改应该是这个。

@Override
protected void paintComponent(Graphics g) {
    super.paintComponent(g);
    Graphics2D g2 = (Graphics2D) g;
    g2.drawImage(image, 0, y, 800, 600, null);
    g2.drawImage(image2, 0, y2, 800, 600, null);
}

始终调用超级paintComponent,并且从不在paint component方法内重新绘制。