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
package zeiterfassung.gui.style;


import java.awt.Dimension;
import java.awt.Graphics;
import java.awt.Image;
import java.awt.Toolkit;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import java.net.URL;

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.setLayout(null);
		this.setPreferredSize(new Dimension(500, 50));
	}

	@Override
	protected void paintComponent(Graphics g) {
		super.paintComponent(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
Urs

(I'm sorry for my bad english)
LVL 1
innovasoftAsked:
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
http://stackoverflow.com/questions/1851151/resize-required-to-view-images-in-java-applet
0
 
innovasoftAuthor Commented:
great! That works!

Thanks a lot!
0
 
objectsCommented:
0
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.