Muneeb Rehman
Muneeb Rehman

Reputation: 129

Drawing a lot of images in paintcomponent method is time consuming

for (int i = 0; i < bricksList.size(); i++) {
 BufferedImage image;
 try {

            image = ImageIO.read(new File(bricksList.get(i).img));

            g.drawImage(image, bricksList.get(i).x, bricksList.get(i).y, null); 
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }   
    }

I am trying to draw 80 images using paintComponent() method. I also have another object which when I press right arrow key, keeps on moving right, when pressed left arrow key, it keeps on moving left, and so on (using keypressed event). But as every time paint component is called so the movement of that other movable object becomes very slow. How can I give a smooth running. How can I stop the bricks to get painted every time?

Upvotes: 1

Views: 58

Answers (2)

ControlAltDel
ControlAltDel

Reputation: 35011

You can speed up your printComponent method by a huge factor by loading your images beforehand

Create a list like BricksListImgs, in your constructor, do

Image BricksListImgs[];

MyConstructor () {
  BricksListImgs = new BricksListImgs[bricksList.size()];
  for (int i = 0; i < bricksList.size(); i++) {
    BricksListImgs[i] = ImageIO.read(new File(bricksList.get(i).img));
  }
}

Then draw the images from BriksListImgs in your paintComponent method

Upvotes: 1

John Bollinger
John Bollinger

Reputation: 180201

Supposing that your code excerpt comes out of your paintComponent() method, you are doing far more work there than you ought to do. On every update, your paintComponent() must read each file from disk (I/O is very costly), and construct a BufferedImage from its contents (not necessarily cheap). Then it just discards the image, which seems likely to be at least tens of kB in size, which will eventually start putting pressure on the GC.

Unless you have some reason to expect that the image files will be modified while your program is running (and maybe even if they will be modified) you could dramatically improve performance by reading all the files once each, and holding on to the BufferedImage objects for repeated use by paintComponent(). If the relative positions of the images do not change, then you could even consider constructing one big image from their contents, and letting paintComponent() paint just that.

Upvotes: 2

Related Questions