Question

Like the title says. I am executing a For loop in my Game.java file(which is where "Main" is located too). and it is Creating massive lag. Only occurs when i am executing a Method from another .java . This is where i execute it in the "Game.java" (Notice: it is a class inside the Game.java) :

    public class DrawPanel extends JPanel{
    /**
     * 
     */
    private static final long serialVersionUID = 1L;

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

    }

    public void paint(Graphics g) {
        Graphics2D g2d = (Graphics2D) g;
        super.paint(g2d);
        Player.draw(g2d);

        for(int i = 0;i < 640;i+=16)
            block.createBlock(g2d,i,382,"Dirt");

        for(int i = 0;i < 640;i+=16)
            for(int x = 398;x < 446; x += 16)
            block.createBlock(g2d,i,x,"Dirt_WO_Grass");

        repaint();
    } 
}

and this is the method in Block.java :

class Block {


public void createBlock(Graphics g, int posx,int posy,String name){
    BufferedImage block = null;
    try {

        block = ImageIO.read(new File("res/"+name+".png"));

        } catch (IOException e) {
        e.printStackTrace();
        }
        g.drawImage(block, posx, posy, null);
    }

}
Was it helpful?

Solution

From what I can see, "massive lag" should be an understatement :)

You need to refactor your algorithm to cache the image from ImageIO and not read it from file 200 times every paint call.

Side note, performance issues are almost never going to be from calling a method in another class. Java is essentially designed to do that.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top