datalogo
Return to Unit Menu |  JavaBitsNotebook.com | MathBits.com | Terms of Use  | JavaMathBits.com

Insert Background Image

The use of images (pictures) make an application more appealing and often more informative. When working in Swing, GIF, PNG, and JPG image formats work best. This section will place an image in a JPanel as a background image. The goal will be to then place drawings or animation on "top" of the background.

Be sure to place (or store) your image in the same file location on your computer as the compiled code. Example: "src/Image.jpg"

For the example on this page, the graphic shown at the right will be used. The graphic is a jpeg whose size is 350 pixels by 350 pixels.

This graphic (or any graphic to be used) must be stored in "src/Network.jpg" before running the program.

When working in a Swing GUI, the image must be an object of the ImageIcon class, which accepts a file name as an argument and then converts that file to an ImageIcon object.

Network
Network.jpg    (350 x 350 pixels)

 

Let's see what is involved in inserting an image (picture) into a Java JPanel.

New coding terms:
reddot Image: this is a type of variable. It will be used to hold the background image we will be loading.

reddot ImageIcon - an ImageIcon object is a picture.
The code ImageIcon icon = new ImageIcon("picture.jpg"); creates an ImageIcon object.

reddot public Image getImage() - returns an Icons image

reddot g.drawImage(img, x, y, null) - a built-in method that draws the specified image with its top-left corner at (xy) in this graphics context's coordinate space. Transparent pixels in the image do not affect whatever pixels are already there. [The last parameter is there for technical reasons and will be either null or this. A non-null value is needed only when the complete image may not be available, or not fully loaded.]

It is possible to scale the image as it is drawn to a specified width and height.
g.drawImage(img, x, y, width, height, null);

When setting the size of the frame, allow for the overlapping of the edges of the frame on your image. This image of 350 pixels by 350 pixels needed a frame of 365 by 395.

dividerdash
Sample Coding

BacGroundImagePic

BKimagepic

divider
Return to Unit Menu |  JavaBitsNotebook.com | MathBits.com | Terms of Use  | JavaMathBits.com

Notice: These materials are free for your on-line use at this site, but are not free for the taking.
Please do not copy these materials or re-post them to the Internet, as it is copyright infringement.
If you wish hard-copies of these materials, refer to our subscription area, JavaMathBits.com.
Help us keep these resources free. Thank you.