Link to home
Start Free TrialLog in
Avatar of innovasoft
innovasoft

asked on

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)
ASKER CERTIFIED SOLUTION
Avatar of for_yan
for_yan
Flag of United States of America image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
Avatar of innovasoft
innovasoft

ASKER

great! That works!

Thanks a lot!
Avatar of Mick Barry