Skip to main content

Image as background in GUI

1 reply [Last post]
mussa
Offline
Joined: 2006-02-17
Points: 0

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() {

super("Demo");

setSize(800,600);
JPanel content = new JPanel();

((JPanel)getContentPane()).setOpaque(false);
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) {
System.exit(0);
}
};
addWindowListener(l);
setVisible(true);
}
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
Offline
Joined: 2006-02-17
Points: 0

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...

Basically
[code]
protected Image getBackgroundImage() {
// return you background image here
}

protected void paintComponent(Graphics g) {
super.paintComponent(g);

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

g.translate(insets.left, insets.top);

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

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

g.translate(-insets.left, -insets.right);
}
[/code]

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

Happy Coding...