Skip to main content

Image as background in GUI

1 reply [Last post]
Joined: 2006-02-17

I want to implement a GUI which uses image as background. I uses JFrame. I managed to set image as backround. When I resize the window I would like that image(background) resizes too.

Thanks for helping me!

Here is my code:

package musa1;

import javax.swing.*;
import java.awt.*;
import java.awt.event.*;

public class TestFrame extends JFrame {
public TestFrame() {


JPanel content = new JPanel();

ImageIcon earth = new ImageIcon("D:/javaproject/proba.jpg");
JLabel backlabel = new JLabel(earth);
getLayeredPane().add(backlabel, new Integer(Integer.MIN_VALUE));
backlabel.setBounds(0,0,earth.getIconWidth(), earth.getIconHeight());
setLocation(200, 100);
WindowListener l = new WindowAdapter() {
public void windowClosing(WindowEvent e) {
public static void main(String[] args) {
new TestFrame();

Reply viewing options

Select your preferred way to display the comments and click "Save settings" to activate your changes.
Shane Whitehead
Joined: 2006-02-17

There are probably a couple of approaches you could take to achieve this, I think the better approach for you would be to create a custom Frame or Component, where the paintComponent method has been overridden and you perform the rescaling process within, I think these would be the eaiser approaches for what you want to achieve...

protected Image getBackgroundImage() {
// return you background image here

protected void paintComponent(Graphics g) {

Insets insest = getInsets();
int width = getWidth() - insets.left - insets.right;
int height = getHeight() - - insets.bottom;


Image img = getBackground().getScaledInstance(width, height, Image.SCALE_SMOOTH);

g.drawImage(img, 0, 0, this);

g.translate(-insets.left, -insets.right);

That will ensure that your image is always scaled to the size of the underlaying component...

Happy Coding...