Background image in a panel

To put an image in a background of a panel, you fist have to disable regular background color painting (setOpaque(false)), and then override the paintComponent() method. In the new paintComponent() method, first draw the background image, and then call super.paintComponent() to draw the rest of the panel over the background.

	public final void paintComponent(Graphics g) {
			if (background!=null) g.drawImage(background, 0,0, null);
			
			super.paintComponent(g);		
	}

The selected version of drawImage does not scale the image or specify the background color, you can choose a different version of that method if you need.

Remember to set the opaque property to false, and to do so in all sub-containers and components put in the panel with a background image.

See also Transparency for more detail on issues with transparency and opaque property, and Frame Background Image Packing.

To paint an arbitrary background without modifying the existing component, you can try this approach (which works on anything that is ordinarily non-opaque).

 

Comments? Corrections? Contact us or Login to edit pages directly (registration is free and takes less than displaying a JLabel)
  howto/background_image.txt · Last modified: 2006/10/04 19:24 by 86.133.133.175 (gojko)
 
Recent changes | RSS changes | Table of contents | News Archive | Terms And Conditions | Register