user1432962
user1432962

Reputation: 25

Loading bufferedImage disables JPanel's paintCompontent method

I have a slight problem with BufferedImage and JPanel. I am creating a game with some 2d animation.

Basically i have an animationHandler that will loop through the pictures and depending on the rotation will also display it correctly. But the problem is - when I load in the pictures my Jpanel wont draw anything. It doesnt event matter if I comment out the custom paint methods - the paintComponent method wont draw anything and it seems like it skips the paintCompontent method. Even though the game doesnt crash and the timer still is running - it wont use the paintComponent method in an extended JPanel.

The class that contains the timer - calls the JPanel throught JPanel.repaint();

Here is the loadImg method

/**
 * Test method to check animationHandler and bufferedImgs
 */
private void loadImages() {
    BufferedImage b_1;
    BufferedImage b_2;
    BufferedImage b_3;
    BufferedImage b_4;
    BufferedImage b_5;

    BufferedImage[] imgs = new BufferedImage[5];
    try {
        b_1 = ImageIO.read(new File("warlock1.png"));
        b_2 = ImageIO.read(new File("warlock2.png"));
        b_3 = ImageIO.read(new File("warlock3.png"));
        b_4 = ImageIO.read(new File("warlock4.png"));
        b_5 = ImageIO.read(new File("warlock5.png"));

        imgs[0] = b_1;
        imgs[1] = b_2;
        imgs[2] = b_3;
        imgs[3] = b_4;
        imgs[4] = b_5;

        animationHandler.addAnimation(imgs);
    } catch (Exception e) {
        e.printStackTrace();
    }
}

Cheers!

Upvotes: 2

Views: 200

Answers (1)

Hovercraft Full Of Eels
Hovercraft Full Of Eels

Reputation: 285403

You're could possibly be loading images on the Swing event thread or EDT (Event Dispatch Thread), and since the EDT is responsible for all Swing graphics and user interactions, this will freeze your Swing application until the loading is complete. The solution: load the images on a background thread such as can be obtained from a SwingWorker object. Please check out the Concurrency in Swing tutorial for more on this subject.

Also, if possible, and if the images aren't too large, it is usually best to load the images once and then hold a reference to them or to an ImageIcon.

And finally, whatever you do, don't load images inside of the paintComponent(...) method. This method must be lean and mean -- as fast as possible, and it should concern itself only with painting and nothing else. Else your program's responsiveness could become pitifully slow.

Also, regarding:

it wont use the paintComponent method in an extended JPanel.

You might want to show us this code.

Upvotes: 5

Related Questions