Preload image?

Hello everybody

I've coded my own JPanel. This panel should have a background-image that will be streched to the whole width and another image that will always appear on the right side of the panel (even if you resize it). Here's my code so far

import java.awt.Dimension;
import java.awt.Graphics;
import java.awt.Image;
import java.awt.Toolkit;
import java.awt.image.BufferedImage;

import javax.imageio.ImageIO;
import javax.swing.*;

public class Header extends JPanel {	
	private Image headerBild = this.getToolkit().getImage(this.getClass().getResource("/images/header.jpg"));
	private Image headerBG = this.getToolkit().getImage(this.getClass().getResource("/images/headerBg.jpg"));
	public Header() {
		this.setPreferredSize(new Dimension(500, 50));

	protected void paintComponent(Graphics g) {
		int x = this.getWidth() - headerBild.getWidth(null);
		g.drawImage(headerBG, 0, 0, this.getWidth(), this.getHeight(), null, null);
		g.drawImage(headerBild, x, 0, 340, 60, null, null);
		g.fillRect(0, 0, 20, 20);

Open in new window

As you can see, I implemented my own paintComponent-method that draws the two images. For testing, I also added a fillRect, so I can see if the method was called.

Now I start my application with a JFrame that includes this panel. In the first moment, there's only the black rectangle, but no images. If I move the JFrame, the two images appear. It's like they haven't loaded the first time paintComponent is called.

Is there a way I can "preload" these images or how can I handle this?

Thank you

(I'm sorry for my bad english)
Who is Participating?
for_yanConnect With a Mentor Commented:

check the solution at the bottomm of this trail,
maybe youi have different issue, but still check
innovasoftAuthor Commented:
great! That works!

Thanks a lot!
Question has a verified solution.

Are you are experiencing a similar issue? Get a personalized answer when you ask a related question.

Have a better answer? Share it in a comment.

All Courses

From novice to tech pro — start learning today.